0

From: 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";
}

Second argument is a predicate:

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

What is that [] with doing there? How is writing that condition i == 1 inside wait different from this:

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 );
}
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • I'm sure there are duplicates, but before anyone find them read about [*lambda expressions*](http://en.cppreference.com/w/cpp/language/lambda). – Some programmer dude Aug 03 '18 at 05:53
  • Your initial `(i == 1)` check in your prospect equivalence is not protected under the mutex. It is in the lambda case (as it should be if it is part of your predicate data, and it certainly appears that is the case). – WhozCraig Aug 03 '18 at 05:58

0 Answers0