31

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.

jotik
  • 17,044
  • 13
  • 58
  • 123
emesx
  • 12,555
  • 10
  • 58
  • 91

2 Answers2

37

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.

Dave S
  • 20,507
  • 3
  • 48
  • 68
  • 6
    "you do have to ensure that the given thread has only locked the recursive mutex once" -> which means you cannot use a condition on a recursive mutex, doesn't it? I mean the purpose of a condition is to synch with other threads, and that won't work if the mutex is not guaranteed to be unlocked during the wait. – Hugo Maxwell Mar 04 '16 at 03:57
  • 3
    @HugoMaxwell It depends on your use case. If you know you are only 1 level deep in your locks, then you can use it with the condition. For example, if the recursive nature of the mutex is only used on the signaling side of the condition, it will work fine. – Dave S Mar 04 '16 at 11:36
3

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>.

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107