Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event notification without mutex

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.

like image 358
qble Avatar asked Apr 08 '13 14:04

qble


2 Answers

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.

like image 149
Stephan Dollberg Avatar answered Oct 13 '22 18:10

Stephan Dollberg


In some threading models (although I doubt in modern ones) the mutex is needed to protect the condition variable itself (not the object you're synchronizing) from concurrent access. If the condition variable wasn't protected by a mutex you could encounter problems on the condition itself.

See Why do pthreads’ condition variable functions require a mutex?

like image 41
Mark B Avatar answered Oct 13 '22 17:10

Mark B