Marie
Marie

Reputation: 1

Undefined reference for boost::mutex in struct

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;
};

Upvotes: 0

Views: 1353

Answers (1)

Matthias247
Matthias247

Reputation: 10396

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.

Upvotes: 1

Related Questions