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?
#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; }
source share