在線程A等待條件變量之前的一段時間內,它必須持有一個互斥鎖。最簡單的解決方案是確保線程B在調用notify_all時保持相同的互斥體。因此,像這樣:
std::mutex m;
std::condition_variable cv;
int the_condition = 0;
Thread A: {
std::unique_lock<std::mutex> lock(m);
do something
while (the_condition == 0) {
cv.wait(lock);
}
now the_condition != 0 and thread A has the mutex
do something else
} // releases the mutex;
Thread B: {
std::unique_lock<std::mutex> lock(m);
do something that makes the_condition != 0
cv.notify_all();
} // releases the mutex
這保證了線程B只做了notify_all()之前線程A獲取該互斥鎖或當線程A的條件變量的等待。
雖然這裏的另一個關鍵是等待the_condition的while循環成爲true。一旦A有互斥體,任何其他線程都不可能改變the_condition,直到A測試the_condition,發現它爲假,並開始等待(從而釋放互斥體)。
問題是:你真的在等待的是the_condition的值變成非零,std :: condition_variable :: notify_all只是告訴你線程B認爲線程A應該醒來並重新測試。
你在使用什麼庫?什麼OS? – 2013-04-09 20:56:30
使用信號量。 – 2013-04-09 21:01:07