Reputation: 4726
I am having difficulty understanding the condition variable statement
cv.wait(lk, []{return i == 1;});
from this link
what role does the lambda function play here.
Does the above statement mean "Stop blocking when the mutex held by the unique_lock lk is free and i==1 "
Upvotes: 0
Views: 92
Reputation: 119
If you look at the type definitions for the parameters, the second parameter must be a predicate. The lambda function is there so that it satisfies the Predicate type. You can't just put in: "i == 1", since it isn't a function. Since the writer doesn't want to write a whole new function that will only ever be called by this lock, s/he wrote in a lambda function to satisfy the Predicate type. http://en.cppreference.com/w/cpp/concept/Predicate
And yes, the statement means to block the thread until both conditions are satisfied: The lock is free and i == 1.
Upvotes: 0
Reputation: 858
Predicate is used to check if the wait condition should go to waiting state again or stop blocking the thread so the thread will continue running. When you awake the wait condtition with notify then it makes a check using predicate and decides what to do next - sleep again or let the thread keep working.
There is a self explaining code on the link provided by you:
while (!pred()) {
wait(lock);
}
Upvotes: 1
Reputation: 5851
The wait
won't exit until the condition defined by the lambda function is satisfied (i.e., until it returns true
).
Upvotes: 0