Reputation: 1276
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.
Upvotes: 25
Views: 12126
Reputation: 715
C++20 provides std::atomic::wait
. https://en.cppreference.com/w/cpp/atomic/atomic/wait
It’s supposed to be faster. On Linux, it can be implemented with futex(2)
. But it’s also possible that a C++ library implements it with mutex.
Upvotes: 1
Reputation: 34608
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.
Upvotes: 16
Reputation: 136495
I have some object, which already internally synchronized - I don't need mutex to protect it. One thread should wait for some event associated with that object, and others would notify.
If you don't hold the mutex the waiting thread is going to miss notifications, regardless whether you use condition_variable
or condition_variable_any
with the internal mutex.
You need to associate at least one bit of extra information with the condition variable, and this bit should be protected by a mutex.
Upvotes: 1
Reputation: 96291
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?
Upvotes: 7