简体   繁体   English

线程何时从condition.wait()中唤醒

[英]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). 如果checkcondition()返回false导致.wait进入睡眠(阻止)状态。 When does .wait check the predicate again ?? .wait什么时候再次检查谓词?

C++11 30.5.1 "Class condition_variable" explains the behavior you can count on. C ++ 11 30.5.1“ class condition_variable类”说明了可以依靠的行为。 There are 3 things that will unblock a thread blocked inside a condition_variable::wait() call. 有3件事将解除阻塞condition_variable::wait()调用内阻塞的线程。 The function will unblock: 该函数将解除阻止:

  • when signaled by a call to notify_one() 当通过调用notify_one()发出信号时
  • when signaled by a call to notify_all() 当通过调用notify_all()发出信号时
  • spuriously 虚假地

In a wait() call that takes a predicate, the compiler generates code that acts like: 在带有谓词的wait()调用中,编译器生成的代码类似于:

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

So if the predicate returns false (or equivalent), the wait() will be called again. 因此,如果谓词返回false (或等效值),则将再次调用wait() 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. 通常,谓词应“匹配”导致notify_one()notify_all()被调用的事件。

When you call cv.notify_one , the waiting thread ( one of the waiting threads, if there are more than one) will wake up. 当您调用cv.notify_one ,等待线程( 一个等待线程,如果有多个)将被唤醒。

The thread that just woke up will then lock the mutex and call this->checkcondition() . 刚醒来的线程将锁定互斥锁并调用this->checkcondition() If that returns true, it will return from wait . 如果返回true,它将从wait返回。 Otherwise, it will unlock the mutex again and go back to sleep. 否则,它将再次解锁互斥锁并返回睡眠状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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