我一直试图让一个项目摆脱每个boost参考并切换到纯C++ 11.
有一次,创建了线程工作者,它等待一个障碍来给出'go'命令,完成工作(通过N个线程传播)并在所有这些完成时同步.基本思想是主循环给出了go命令(boost :: barrier .wait())并等待具有相同函数的结果.
我在一个不同的项目中实现了一个基于Boost版本的定制Barrier,一切都运行得很好.实施如下:
Barrier.h:
class Barrier {
public:
Barrier(unsigned int n);
void Wait(void);
private:
std::mutex counterMutex;
std::mutex waitMutex;
unsigned int expectedN;
unsigned int currentN;
};
Run Code Online (Sandbox Code Playgroud)
Barrier.cpp
Barrier::Barrier(unsigned int n) {
expectedN = n;
currentN = expectedN;
}
void Barrier::Wait(void) {
counterMutex.lock();
// If we're the first thread, we want an extra lock at our disposal
if (currentN == expectedN) {
waitMutex.lock();
}
// Decrease thread counter
--currentN;
if (currentN == 0) {
currentN = expectedN;
waitMutex.unlock(); …
Run Code Online (Sandbox Code Playgroud)