Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between notify_all() and notify_one() of std::condition_variable?

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!

like image 454
Yun Huang Avatar asked Jan 26 '12 08:01

Yun Huang


People also ask

What is the difference between Notify_one and Notify_all?

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.

What is std :: Condition_variable?

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 .

What does notify_ one do?

The notify_one() member function unblocks one of the threads that are blocked on the specified condition variable at the time of the call.

How do I notify a specific thread in C++?

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.


1 Answers

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.

like image 160
GManNickG Avatar answered Oct 18 '22 09:10

GManNickG