How to make sure that all sub threads are waiting for a condition variable?

I am running the following code snippet. This code will create 5 sub threads and 1 main thread. All subordinate threads are waiting for the main thread to make the data ready, and when the data is ready, all the subordinates will notify in order to start processing.

My question is that before the slave threads begin to wait for conditional_variable , the main thread will make the data ready and report the expected threads. In this case, some threads that were waiting will receive a notification and begin processing, but those that did not wait will begin to wait for a notification that will NEVER arrive.

If you run this example, this will not happen, but I’m looking for a way to make sure that all the sub threads are waiting for a notification and then notify about it. Do you know how I can do this?

 /* Condition Variables - Many waiting threads Shows how one condition variable can be used to notify multiple threads that a condition has occured. * Part of "Threading with Boost - Part IV: Condition Variables", published at: http://antonym.org/boost Copyright (c) 2015 Gavin Baker < gavinb@antonym.org > Published under the MIT license, see LICENSE for details */ #include <cstdio> #include <boost/thread.hpp> boost::condition_variable data_ready_cond; boost::mutex data_ready_mutex; bool data_ready = false; void master_thread() { printf("+++ master thread\n"); // Pretend to work printf(" master sleeping...\n"); boost::chrono::milliseconds sleepDuration(750); boost::this_thread::sleep_for(sleepDuration); // Let other threads know we're done printf(" master notifying...\n"); data_ready = true; data_ready_cond.notify_all(); printf("--- master thread\n"); } void slave_thread(int id) { printf("+++ slave thread: %d\n", id); boost::unique_lock<boost::mutex> lock(data_ready_mutex); while (!data_ready) { data_ready_cond.wait(lock); } printf("--- slave thread: %d\n", id); } int main() { printf("Spawning threads...\n"); boost::thread slave_1(slave_thread, 1); boost::thread slave_2(slave_thread, 2); boost::thread slave_3(slave_thread, 3); boost::thread slave_4(slave_thread, 4); boost::thread master(master_thread); printf("Waiting for threads to complete...\n"); slave_1.join(); slave_2.join(); slave_3.join(); slave_4.join(); master.join(); printf("Done\n"); return 0; } 
0
source share
1 answer

You have a race condition - the installation flag and notification of subordinate threads is not atomic. Therefore, you need to lock data_ready_mutex before changing the data_ready flag in the main thread. This will eliminate the race condition, the slave thread will either see data_ready false, or go to wait for the condition variable and be notified, or it will block the lock only after data_ready set to true , and therefore it will not wait at all.

+3
source

Source: https://habr.com/ru/post/1244365/


All Articles