1

It's useful to have the ability to assert in debug mode, with reasonably small overhead, whether a mutex is locked. Viewing the known options, I've chosen to implement this using an std::mutex subclass due to the low overheads.

The interface of the subclass is a superset of that of std::mutex, and so most things work well with it. E.g., std::unique_lock is templated to utilize any lock type that has a specific interface.

The problem is with std::condition_variable, in particular the wait members, e.g.:

template<class Predicate>
void wait(std::unique_lock<std::mutex> &lock, Predicate pred);

As can be seen, the method requires a very specific unique_lock/mutex combination. Unfortunately, also, the Liskov principle doesn't extend for container<derived> being converted into container<base>.

I don't understand

  1. why this is so?

Even if the intent was to enforce the use of std::unique_lock, then why couldn't the following be used:

template<class Predicate, class Lock=std::mutex>
void wait(std::unique_lock<Lock> &lock, Predicate pred);
  1. how to reasonably get around this?

Edit

As explained by @Lingxi, and further pointed out by @T.C, the absolutely correct and very simple solution here is to use condition_variable_any, which was designed for stuff like this.

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • I'm wondering how you will implement the `is_locked` interface based on `std::mutex`. – Lingxi May 08 '15 at 11:50
  • Not sure what you mean. Are you referring to my link above (in the first paragraph)? – Ami Tavory May 08 '15 at 11:54
  • 1
    http://stackoverflow.com/questions/8758353/whats-the-difference-between-stdcondition-variable-and-stdcondition-variable – T.C. May 08 '15 at 14:10

1 Answers1

3

Try std::condition_variable_any. It has a template version of wait.

Lingxi
  • 14,579
  • 2
  • 37
  • 93
  • Perfect! I was not aware of its existence. Of course, now I am a bit curious why there are two separate classes, instead of one (possibly with a specialization for instantiating the method with ``std::lock_guard``), – Ami Tavory May 08 '15 at 11:56
  • 1
    `std::condition_variable` may allow some optimization that is not feasible to `std::condition_variable_any`, I guess. – Lingxi May 08 '15 at 12:01