0

I want to use a boost::mutex for the function add of my struct Cell. Here is the definition of my struct in Detector.h

class Detector {

private:
    struct  Cell{
        static boost::mutex mutex_;
        double energy;
        double sqrt_energy;
        int histories;

        inline Cell(): energy(0.f), sqrt_energy(0.f), histories(0.f) {
            boost::mutex mutex_;  //I tried with and without this line
        };  

        inline void add(double new_energy) {
            mutex_.lock();
            energy += new_energy;
            sqrt_energy += new_energy*new_energy;
            ++histories;
            mutex_.unlock();
        };
    };

    typedef std::vector<Cell> CellVector;
    CellVector EnergyPrimary;

}

And I use my function add in Detector.cpp on a vector of Cell.

Dectetor::Detector() : {
  nVoxelX=1024;
  nVoxelY=1024;
  size=nVoxelX*nVoxelY;
  EnergyPrimary=CellVector(size);
}

void Detector::Score(int cellID, double new_energy) {
  EnergyPrimary[cellID].add(new_energy);
}

When I try to compile it I have a undefined reference error for mutex_.lock() and mutex_.unlock(). But why is it working before when I overload the operator += with a similar function (and when I called EnergyPrimary[cellID].energy += new_energy;)?

inline bool operator+= (double new_energy) {
    mutex_.lock();
    energy += new_energy;
    mutex_.unlock();
    return false;
};
Marie
  • 1
  • 2
  • Are you including the header file? Your compiler knows where to find boost? – Jepessen Nov 11 '16 at 22:50
  • Your 'mutex_' is static but I don't see where you define it. You really want only one mutex for all cell and all detectors? – qPCR4vir Nov 11 '16 at 23:11
  • Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Danh Nov 12 '16 at 05:49
  • Jepessen : Yes I include it and yes my compiler finds boost. My error is undefined reference to `Detector::Cell::mutex_' – Marie Nov 14 '16 at 18:34
  • qPCR4vir : I tried to define it (I edit my post with this line), but it still doesn't work. I want one mutex per cell. – Marie Nov 14 '16 at 18:34
  • @Marie That's a linker error, not a compiler error. – David Schwartz Nov 14 '16 at 18:39

1 Answers1

1

You have defined mutex_ as a static member of the class, which means it is not a per-instance member. Therefore you can't initialize in the constructor. Instead it must be initialized in a source file, in your case most likely Detector.cpp.

The code for the initialization should be:

boost::mutex Detector::Cell::mutex_;

If you don't want it to be a static member (you want one mutex per Cell) remove the static qualifier.

Matthias247
  • 9,836
  • 1
  • 20
  • 29
  • Thank you, I changed my static mutex to a pointer to mutex which I initialise in my inline Cell() function and it seems to work. – Marie Nov 18 '16 at 19:55