Do I need to synchronize std::condition_variable/condition_variable_any::notify_one
?
As far as I can see, if lost of notifications is acceptable - it is OK to call notify_one
not protected (by mutex for example).
For instance, I saw following usage patterns (sorry, don't remember where):
{
{
lock_guard<mutex> l(m);
// do work
}
c.notify_one();
}
But, I inspected libstdc++ sources, and I see:
condition_variable::notify_one
void condition_variable::notify_one() noexcept
{
int __e = __gthread_cond_signal(&_M_cond);
// XXX not in spec
// EINVAL
if (__e)
__throw_system_error(__e);
}
and condition_variable_any::notify_one:
void condition_variable_any::notify_one() noexcept
{
lock_guard<mutex> __lock(_M_mutex);
_M_cond.notify_one();
}
And here is layout of condition_variable_any:
class condition_variable_any
{
condition_variable _M_cond;
mutex _M_mutex;
// data end
I.e. it is just thin wrapper around condition_variable+mutex.
So, questions:
- Is it thread-safe to not protect
notify_one
by mutex for eithercondition_variable_any
orcondition_variable
? - Why implementation of condition_variable_any uses additional mutex?
- Why implementation of
condition_variable_any::notify_one
andcondition_variable::notify_one
differs? Maybecondition_variable::notify_one
requires manual protection butcondition_variable_any::notify_one
doesn't? Is it libstdc++ bug?