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

C++MultithreadingC++11Condition Variable

C++ Problem Overview


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!

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYun HuangView Question on Stackoverflow
Solution 1 - C++GManNickGView Answer on Stackoverflow