In my application, many threads notify a waiting thread. Sometimes these notifications are very close to each other in time and the waiting thread misses the notification. Is there any easy way to counter this issue? A small example code is given below. In the code, the task2 notifies the waiting thread but the waiting thread, waitingForWork, miss the notification.
#include <condition_variable> #include <iostream> #include <thread> std::mutex mutex_; std::condition_variable condVar; bool dataReady{ false }; void waitingForWork() { for (int i = 0; i < 2; i++) { std::cout << "Waiting " << std::endl; std::unique_lock<std::mutex> lck(mutex_); condVar.wait(lck, [] { return dataReady; }); dataReady = false; std::cout << "Running " << std::endl; } } void task1() { std::this_thread::sleep_for(std::chrono::milliseconds{ 45 }); std::lock_guard<std::mutex> lck(mutex_); dataReady = true; std::cout << "Task1 Done:" << std::endl; condVar.notify_one(); } void task2() { std::this_thread::sleep_for(std::chrono::milliseconds{ 46 }); std::lock_guard<std::mutex> lck(mutex_); dataReady = true; std::cout << "Task2 Done" << std::endl; condVar.notify_one(); } int main() { std::cout << std::endl; std::thread t1(waitingForWork); std::thread t2(task1); std::thread t3(task2); t1.join(); t2.join(); t3.join(); std::cout << std::endl; system("pause"); }
datareadybefore locking and setting it to true to prevent unnecessary locking.