0

我想对我的 struct Cell的函数add使用 boost::mutex 。这是我在 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;

}

我在Cell的向量上使用我的函数add in Detector.cpp 。

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

当我尝试编译它时,mutex_.lock() 和 mutex_.unlock() 出现未定义的引用错误。但是为什么它在我用类似的函数重载运算符 += 之前(以及当我调用 EnergyPrimary[cellID].energy += new_energy;)之前工作?

inline bool operator+= (double new_energy) {
    mutex_.lock();
    energy += new_energy;
    mutex_.unlock();
    return false;
};
4

1 回答 1

1

您已定义mutex_为类的静态成员,这意味着它不是每个实例的成员。因此,您不能在构造函数中进行初始化。相反,它必须在源文件中初始化,在您的情况下很可能是Detector.cpp.

初始化代码应该是:

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

如果您不希望它成为静态成员(您希望每个单元有一个互斥锁),请删除static限定符。

于 2016-11-14T18:33:13.573 回答