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!
Show activity on this post. 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 The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable .
The notify_one() member function unblocks one of the threads that are blocked on the specified condition variable at the time of the call.
If you want to notify a specific thread, use a separate std::condition_variable for it. Do not use that std::condition_variable for other threads.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With