我一直在尝试让一个项目摆脱每个 boost 引用并切换到纯 C++11。
在某一时刻,线程工作者被创建,等待屏障发出“go”命令,完成工作(通过 N 个线程传播)并在所有线程完成时同步。基本思想是主循环给出执行顺序(boost::barrier.wait())并用相同的函数等待结果。
我在另一个项目中实现了一个基于 Boost 版本的定制屏障,一切正常。实施如下:
屏障.h:
class Barrier {
public:
Barrier(unsigned int n);
void Wait(void);
private:
std::mutex counterMutex;
std::mutex waitMutex;
unsigned int expectedN;
unsigned int currentN;
};
屏障.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();
currentN = expectedN;
counterMutex.unlock();
} else {
counterMutex.unlock();
waitMutex.lock();
waitMutex.unlock();
}
}
此代码已在 iOS 和 Android 的 NDK 上使用,没有任何问题,但在 Visual Studio 2013 项目上尝试时,似乎只有锁定互斥锁的线程才能解锁它(断言:解锁无主互斥锁)。
是否有任何可用于 C++11 的非旋转(阻塞,例如这个)屏障版本?我只能找到使用忙等待的障碍,这是我想阻止的(除非真的没有理由这样做)。