Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you combine std::recursive_mutex with std::condition_variable?

Can you combine std::recursive_mutex with std::condition_variable, meaning do something like this:

std::unique_lock<std::recursive_mutex> lock(some_recursive_mutex) some_condition_var.wait(lock); 

If it's not allowed, then why not?

I am using VC++11.

like image 861
emesx Avatar asked Jan 14 '13 17:01

emesx


People also ask

What is std :: Condition_variable?

std::condition_variable The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable .

What does condition variable wait do?

condition_variable::wait wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (bool(stop_waiting()) == true).

How do conditional variables work in C++?

A condition variable is an object able to block the calling thread until notified to resume. It uses a unique_lock (over a mutex ) to lock the thread when one of its wait functions is called.

What is thread condition?

A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None , it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock.


2 Answers

You can, if you use std::condition_variable_any, which allows for any type of object that supports the Lockable concept.

However, in the case of recursive mutex, you do have to ensure that the given thread has only locked the recursive mutex once, since the condition variable only will use the unlock method on the unique_lock once during the wait.

like image 197
Dave S Avatar answered Sep 23 '22 12:09

Dave S


You can do that with a std::condition_variable_any which can take any kind of lockable but plain std::condition_variable is specialized for std::unique_lock<std::mutex>.

like image 21
Stephan Dollberg Avatar answered Sep 24 '22 12:09

Stephan Dollberg