爲了學習boost :: thread的combinatorics,我爲鎖定一個普通的互斥體(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 10:45:39