为了学习 boost::thread 的组合,我正在为锁定公共互斥锁 (M) 的线程实现一个简单的屏障 (BR)。但是,据我在去 BR.wait() 时得到的,互斥锁上的锁没有被释放,所以为了让所有线程到达 BR,需要手动释放 M 上的锁。所以我有以下代码:
boost::barrier BR(3);
boost::mutex M;
void THfoo(int m){
cout<<"TH"<<m<<" started and attempts locking M\n";
boost::lock_guard<boost::mutex> ownlock(M);
cout<<"TH"<<m<<" locked mutex\n";
Wait_(15); //simple wait for few milliseconds
M.unlock(); //probably bad idea
//boost::lock_guard<boost::mutex> ~ownlock(M);
// this TH needs to unlock the mutex before going to barrier BR
cout<<"TH"<<m<<" unlocked mutex\n";
cout<<"TH"<<m<<" going to BR\n";
BR.wait();
cout<<"TH"<<m<<" let loose from BR\n";
}
int main()
{
boost::thread TH1(THfoo,1);
boost::thread TH2(THfoo,2);
boost::thread TH3(THfoo,3);
TH2.join(); //but TH2 might end before TH1, and so destroy BR and M
cout<<"exiting main TH \n";
return 0;
}
而 M.unlock() 显然是一个糟糕的解决方案(不使用锁);那么如何(简单地)释放锁?另外:我如何(正确地)在 main() 中等待所有线程完成?(TH2.join() 不好,因为 TH2 可能会先完成...);
请不要建议复飞,例如使用我也可以使用的条件变量,但必须可以在没有它们的情况下直接进行。