[] {return i == 1;}是什么意思,它在std等待和条件变量中如何工作?

时间:2018-08-03 05:51:29

标签: c++ mutex condition-variable

发件人:https://en.cppreference.com/w/cpp/thread/condition_variable/wait

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cerr << "...finished waiting. i == 1\n";
}

第二个参数是谓词:

template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate pred );

[]在那做什么?在i == 1中写入条件wait与此有何不同:

if (i == 1)
{
    std::unique_lock<std::mutex> lk( mutex_association );
    // Do something with `i`
}
else
{
    std::unique_lock<std::mutex> lk( mutex_association );
    cv_association.wait( lk );
}

0 个答案:

没有答案