std :: condition_variable的notify_all()和notify_one()有什么区别? [英] What's the difference between notify_all() and notify_one() of std::condition_variable?
问题描述
当前,我正在C ++ 11中使用std::thread
实现多线程项目.我使用std::condition_variable
同步线程.详细地,一个使用者函数调用std::condition_variable
的wait()
成员函数来等待全局任务队列中的任务,另一个生产者函数生成任务并将其放入队列.但是我不知道std::condition_variable
的notify_all()
和notify_one()
成员函数之间的区别.在生产者函数中应该使用哪个函数?谢谢!
Currently, I am implementing a multi-thread project using std::thread
in C++11. I use std::condition_variable
to synchronize threads. In detail, one consumer function calls wait()
member function of std::condition_variable
to wait for task from a global task queue, another producer function generates and puts tasks into the queue. But I do not know the difference between notify_all()
and notify_one()
member functions of std::condition_variable
. Which function should I use in the producer function? Thanks!
推荐答案
例如,如果条件变量上有十个线程被阻塞,则notify_one()
将仅解除阻塞一个线程,而notify_all()
将对其全部解除阻塞.在您的情况下,您将要使用notify_one()
,这样就不会唤醒没有任何工作在等待它们的线程.
If there are ten threads blocked on the condition variable, for example, notify_one()
will unblock only one thread, while notify_all()
will unblock them all. In your case, you'll want to use notify_one()
so you don't wake up threads that don't have any work waiting for them.
这篇关于std :: condition_variable的notify_all()和notify_one()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!