问题描述
boost::condition_variable cond;
boost::mutex mut;
bool ready = false;
void consumer() {
boost::mutex::scoped_lock lock(mut);
while (!ready) {
cond.wait(lock);
}
}
void producer() {
boost::mutex::scoped_lock lock(mut);
ready = true;
cond.notify_all();
boost::this_thread::sleep(boost::posix_time::seconds(4));
}
参考上面的代码,实际上我在调用notify_all()之后使生产者线程休眠4秒钟.但是,消费者线程实际上在4秒钟后被唤醒.因此,尽管有4秒钟的睡眠时间,但我如何在调用notify_all()之后立即解决并唤醒使用者线程.预先感谢.
Refer to the above code, I actually sleep the producer thread for 4 seconds after I call notify_all(). However, the consumer threads are actually woken up after 4 seconds. So how can I get around this and wake up the consumer threads immediately after I call notify_all() despite the 4 seconds sleep. Thanks in advance.
推荐答案
它与boost :: mutex :: scoped_lock lock(mut);有关.在生产者中.由于示波器在睡眠后结束,因此互斥锁仅在它释放之后释放.
It has to do with the boost::mutex::scoped_lock lock(mut); in producer.As the scope ends AFTER the sleep, the mutex is only released after it.
如果要保留您的scoped_lock,请尝试使用此方法.
Try with that, if you want to keep your scoped_lock.
void producer() {
{
boost::mutex::scoped_lock lock(mut);
ready = true;
cond.notify_all();
}
boost::this_thread::sleep(boost::posix_time::seconds(4));
}
这篇关于增强线程notify_all()和sleep()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!