UPDATE:
It seems to me like my question is not duplicate. My accent on that nuance - we do not need to transfer data. And actually my question - is three different questions.
I have a few questions.
1) std::condition_variable
is everywhere considered as a means of synchronizing access to data. Thus, examples of usage usually look like this:
void put (const T &val) {
std::unique_lock<std::mutex> lock(m_Mtx);
m_Value = val;
m_CondVar.notify_one();
}
T get () {
std::unique_lock<std::mutex> lock(m_Mtx);
m_CondVar.wait(lock);
return m_Value;
}
It's clear. But what if I do not need to transfer data, but only need to wake up the waiting thread (if there is one) - can I, in this case, NOT use the mutex and use code like this?
void put_nolock () {
m_CondVar.notify_one();
}
It is quite not clear from documentation.In the documentation for pthread_cond_signal
can see:
The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().
I can not realize - what exactly does this mean ("however, if predictable scheduling behavior is required...")? My goal is micro-optimization, less mutexes, less potential context switching. So maybe it does not make sense at all and the cost of using mutex + cond_var is equal the cost of using just cond_var?
2) what is the cost of m_CondVar.notify_one()
? Will it be a regular syscall? Does it depends on whether there are waiting threads or that cond_var or not?
3) maybe you know more lightweight way to notify (without or with sending a message, it does not matter) one thread from another?