Suppose there are three threads A, B, and C. B and C suspend at a certain point, waiting for A to signal them to continue. Among the thread synchronization facilities provided by standard C++, std::condition_variable
seems to best fit in here (though still bad). Since std::condition_variable
must be used with a lock, the code for B and C may contain lines like:
{
std::mutex mut;
std::unique_lock<std::mutex> lock(mut);
cond_var.wait(lock); // cond_var is a global variable of type std::condition_variable`
}
Note that mut
is used here not for synchronization purposes at all, but just to fit the signature of std::condition_variable::wait
. With this observation, I'm thinking that maybe we can do better by implementing a dummy lock class, let's say dummy_lock
, and replace std::condition_variable
with std::condition_variable_any
. dummy_lock
meets the BasicLockable requirements with all its methods essentially doing nothing. Thereby, we get code similar to the following:
{
dummy_lock lock;
cond_var.wait(lock); // cond_var is a global variable of type std::condition_variable_any`
}
This, if works at all, should be of higher efficiency than the original one. But the question is, does it even work according to the standard (language-lawyers are apt here)? Even if it works, this is by-no-means an elegant solution. So, do any of you folks have better ideas?
You are working on a false premise.
The mutex does not only protect the condition predicate, it also protects the condition_variable itself.
So the mutex should be at the same scope as the condition_variable and all locks should lock that same mutex.
like this:
// global scope
std::mutex mut;
std::condition_variable cond_var;
// thread scope
{
std::unique_lock<std::mutex> lock(mut);
cond_var.wait(lock);
}
see here: Why do pthreads’ condition variable functions require a mutex?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With