为了学习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可能会先完成...);
请不要建议变通,例如使用条件变量,我也可以使用它们,但它必须可以在没有条件变量的情况下直接实现。
发布于 2012-03-06 18:35:48
类似于:
void THfoo(int m){
// use a scope here, this means that the lock_guard will be destroyed (and therefore mutex unlocked on exiting this scope
{
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
}
// This is outside of the lock
cout<<"TH"<<m<<" unlocked mutex\n";
cout<<"TH"<<m<<" going to BR\n";
BR.wait();
cout<<"TH"<<m<<" let loose from BR\n";
}至于等待,只需在所有线程句柄上调用join (如果它们已经完成,函数将立即返回)
TH1.join();
TH2.join();
TH3.join();发布于 2012-03-06 18:43:31
除了在块中限定boost::lock_guard的作用域之外,您还可以使用可以显式unlock()的boost::unique_lock:
boost::unique_lock<boost::mutex> ownlock(M);
cout<<"TH"<<m<<" locked mutex\n";
Wait_(15); //simple wait for few milliseconds
ownlock.unlock();如果您需要在稍后重新获取互斥之前释放它,这是很有用的。
至于连接,只需对所有线程句柄依次调用join()即可。
发布于 2012-03-06 18:35:27
让它超出范围:
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
}
// 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";
}https://stackoverflow.com/questions/9581841
复制相似问题