Event notification without mutex

c++, c++11, condition-variable, events, multithreading

Solution

Use `std::condition_variable_any` you can use any class with it which implements the BasicLockable Concept.

Given a bad feeling about this I checked the implementation of `std::condition_variable_any` of libc++. It turns out that it uses a plain `std::condition_variable` together with a `std::shared_ptr` to a `std::mutex`, so there is definitely some overhead involved without digging any deeper. (There is some other post here on SO which covers this, though I first have to search that) As a matter of that I would probably recommend to redesign your case so that synchronization is really only done by a mutex protecting a plain condition variable.

Problem

C++11 has the std::condition_variable, its wait function is ``` template< class Predicate > void wait( std::unique_lock<std::mutex>& lock, Predicate pred ); ``` It requires a mutex. As far as I understand - its notify_one can be called without synchronization (I know the idiomatic way is to use it with a mutex). I have an object which is already internally synchronized - so I don't need a mutex to protect it. One thread should wait for some event associated with that object, and others would be notified. How to do such notification without a mutex in C++11? I.e. it is easy to do with a condition_variable, but it needs a mutex. I thought about using a fake mutex type, but std::mutex is nailed in the wait interface. An option is to poll a std::atomic_flag + sleep, but I don't like sleeping.

Original source

Related problems