Preface: I've seen similar questions here, but not one of them seems to answer my question.
Is there a reliable way to make sure that wait() method in consumer thread is called before the first notify_one() call from the producer thread?
Even with unique_lock in the consumer thread, there is a possibility that the producer thread will run first, lock the mutex and call notify() before the consumer calls wait(), therefore, my app will be missing first notify() call.
EDIT: Thanks for all your answers, they did help me. My problem was with first wait-notify() within this consumer loop:
while (!timeToQuit) {
gdcv.wait(gdcondlock);
gdlock.lock();
//spurious wakeup
if (gdQueue.empty()) {
gdlock.unlock();
continue;
}
//some work here
gdlock.unlock();
}
I guess I'll have to write extra code for the first loop iteration.
EDIT2: This loop and second lock(unique_lock btw) are there because there are multiple producers and consumers accessing queue.
EDIT3: The correct way for waiting on this particular thread with the help of boost::lockfree::queue, in case anyone has similar problem:
nfq_data* data;
while (!timeToQuit) {
gdcv.wait(gdlock,[&]{return !gdQueue.empty() || timeToQuit;});
gdQueue.pop(data);
gdlock.unlock();
}
gdlock.lock()andgdlock.unlock()instead of usinglock_guard? Do you dislike simplicity and correctness?lock_guard lg(m); gdcv.wait(lg, [&]{ return gdQueue.empty(); })? This should do the right thing, i.e. return immediately if the condition is true or wait until notified and the condition is true.