Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition variable and shared mutex

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?

like image 305
Kai Mast Avatar asked Jan 21 '16 17:01

Kai Mast


People also ask

What is difference between mutex and condition variable?

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.

Does condition variable need mutex?

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.

Does condition variable wait unlock 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.


Video Answer


1 Answers

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 type unique_lock<mutex>, allowing maximum effciency on some platforms.

like image 79
Stephan Dollberg Avatar answered Oct 15 '22 22:10

Stephan Dollberg