简体   繁体   中英

when does a thread wake up from condition.wait()

I wanted to know when does a thread wake up from a condition I have something like this on the consumer thread

while(true)
                {
                    std::unique_lock<std::mutex> guard(mmutex);
                    cv.wait(guard, [this]{ return this->checkcondition(); } ); //sleeps when does this wake up
                    if(vector.size()>0) 
                    {
                       ....
                    }
                }

This is the producer thread

std::lock_guard<std::mutex> guard(mmutex);
vector.push_back(s);
cv.notify_one();

Now my question is in the statement

cv.wait(guard, [this]{ return this->checkcondition(); } );

if checkcondition() returns false causing .wait to sleep(block). When does .wait check the predicate again ??

C++11 30.5.1 "Class condition_variable" explains the behavior you can count on. There are 3 things that will unblock a thread blocked inside a condition_variable::wait() call. The function will unblock:

  • when signaled by a call to notify_one()
  • when signaled by a call to notify_all()
  • spuriously

In a wait() call that takes a predicate, the compiler generates code that acts like:

while (!pred())
    wait(lock);

So if the predicate returns false (or equivalent), the wait() will be called again. It will not unblock again until one of those three things mentioned before occurs again.

Usually the predicate should "match" the event that caused notify_one() or notify_all() to be called.

When you call cv.notify_one , the waiting thread ( one of the waiting threads, if there are more than one) will wake up.

The thread that just woke up will then lock the mutex and call this->checkcondition() . If that returns true, it will return from wait . Otherwise, it will unlock the mutex again and go back to sleep.

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