I wonder why I can't do this in C++14 (or 17)
std::shared_timed_mutex mutex;
std::unique_lock<std::shared_timed_mutex> lock(mutex);
std::condition_variable var;
while(!some_condition)
var.wait(lock);
Condition variables only seem to work with std::mutex. But why?
While mutex implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data. Without condition variables, the programmer would need to have threads continually polling (possibly in a critical section), to check if the condition is met.
Condition variables are used to wait until a particular condition predicate becomes true. This condition predicate is set by another thread, usually the one that signals the condition. A condition predicate must be protected by a mutex.
The pthread_cond_wait() function atomically unlocks mutex and performs the wait for the condition. In this case, atomically means with respect to the mutex and the condition variable and another threads access to those objects through the pthread condition variable interfaces.
This is defined by the standard to allow for maximum efficiency of the implementation. If you want to use a different lock with condition_variable
you need to use condition_variable_any
. Note that the condition_variable_any
implementation has some overhead though.
Quote from the standard: 30.5 Condition variables
Class
condition_variable
provides a condition variable that can only wait on an object of typeunique_lock<mutex>
, allowing maximum effciency on some platforms.
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