简体   繁体   中英

Calling std::condition_variable::notify_one() multiple times before std::condition_variable::wait() is called

I am struggling to understand the way std::condition_variable is used. Let's say I have Producer and consumer thread and both are operating on same condition_variable . Producer fills the data to process very fast and calls std::condition_variable::notify_one() every time a data is pushed to container. So let's say Producer pushed 10 items and called notify_one() 10 times even before consumer can process data that was added first. Now producer thread exits so it will not call nootify_one() anymore so what will happen to consumer thread who is waiting on condition_variable ? Will previous 9 calls to notify_one() will be queued and consumer will be unblocked 9 times more?

From cppreference ,

If any threads are waiting on *this , calling notify_one unblocks one of the waiting threads.

The thing is, it shouldn't matter. Any consumer using the condition_variable must check if they are allowed to proceed, that is, if there's any available data. In the case you describe they'll find there is, so they won't be suspended and won't require the notification.

Or, said in the other way, they'll be suspended when no data is available, and will wake up only after the producer adds new data and calls notify_one with any suspended consumer.

condition_variable::notify_one() and condition_variable::notify_all() do not record the number of times they've been called. They apply to any threads that are waiting at the time of the call. Threads that wait for the condition variable later are not affected by previous calls. It's up to the program to keep track of whether there's any work pending.

That's why wait() is called from a loop:

while (no_data_ready())
    myvar.wait();

That is, only wait when there's nothing to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM