0

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"); } 
3
  • 2
    Condition variables can not be used as multiple producers and single consumer queue of events that you are seemingly trying to do. Commented Aug 10, 2018 at 11:08
  • 2
    It looks like multiple producer/single consumer. Use a concurrent queue as a communication channel to issue work/events to the consumer. When the worker wakes, it depletes the job queue before returning to sleep/wait. When submitting work to the queue, check the dataready before locking and setting it to true to prevent unnecessary locking. Commented Aug 10, 2018 at 11:10
  • 1
    That's not what condition variables are for. A condition variable allows you to wait for a condition to become true. It doesn't matter how many times it becomes true, only that the condition is true. Commented Aug 10, 2018 at 11:23

1 Answer 1

2

It's a multiple producer single consumer problem. Which is described here: Multiple consumer single producer problem

So basically you have to change your code in a way that each thread have to write notifications into a threadsafe queue. And then your worker thread has to work on this queue and will not miss anymore notifications.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.