在线程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