Multi-threaded control with variable_condition

I have not wrapped myself in a C ++ 11 multi-threaded file yet, but I try to have several threads wait for some event in the main thread, and then everything continues immediately (processing what happened) and wait again when they are processed ... loop into those until they are closed. The following is not entirely true - this is a simpler reproduction of my problem:

 std::mutex mutex; std::condition_variable cv; std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); std::cout << "GO1!\n"; }); std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock); std::cout << "GO2!\n"; }); cv.notify_all(); // Something happened - the threads can now process it thread1.join(); thread2.join(); 

It works ... if I don’t stop at some control points and slow down the situation. When I do this, I see Go1! and then hang, waiting for thread2 cv.wait . What's wrong?

Maybe I should not use the condition variable anyway ... there are no conditions around wait , and there is no data that needs to be protected with the mutex. What should I do instead?

+7
source share
1 answer

You are on the right track ...

Just add a boolean value (protected by a mutex, indicated by a condition variable), which means "go":

 std::mutex mutex; std::condition_variable cv; bool go = false; std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock); std::cout << "GO1!\n"; }); std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock); std::cout << "GO2!\n"; }); { std::unique_lock<std::mutex> lock(mutex); go = true; cv.notify_all(); // Something happened - the threads can now process it } thread1.join(); thread2.join(); 
+5
source

All Articles