Reputation: 3388
From C++11 book on detector and reactor: Detector detects something then asks reactor to do the job:
// Detector:
std::condition_variable cv;
std::mutex m;
bool flag(false);
// ... detect event
{
std::lock_guard<std::mutex> g(m);
flag = true;
}
cv.notify_one();
On the other hand, reactor:
// Reactor
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] {return flag;} )
... ...
}
My question is, if the reactor is triggered first and acquire a lock on the mutex m, will it be deadlock, as the reactor will be blocked on cv.wait and the detector can't get the lock for m?
Upvotes: 0
Views: 83
Reputation: 63735
This is a common pattern and use for std::condition_variable
.
The function std::condition_variable::wait
:
unique_lock
to be passed to it.unique_lock
before waiting.unique_lock
is locked again before exiting.Hopefully, your book will go on to account for spurious wakes. Edit: ... which is not a concern for the predicate form you are using!
Upvotes: 1