During developing a tiny performance-critical part of a program I wondered if there were any significant overhead in calling "notify" on a condition variable if no-one were waiting on it. If someone is waiting on it it it will obviously go into the kernel and wake up that thread and have non-neglible overhead. But what if no-one is waiting? Is that cheap?
And is there a penalty for using the C++11 wrappers around pthread in this particular scenario?
I wrote 4 small test programs. One for each of std::condition_variable::notify_one(), std::condition_variable::notify_all(), pthread_cond_signal() and pthread_cond_broadcast(). The program creates a brief thread to excercise the condition variable to ensure that any lazy resource allocation is not skewing the results. And then it calls the interesting function a million times.
Function | Time | Nanoseconds per call |
---|---|---|
std::condition_variable::notify_one() | 0.004 seconds | 3.884962 |
std::condition_variable::notify_all() | 0.004 seconds | 3.600878 |
pthread_cond_signal() | 0.002 seconds | 2.351499 |
pthread_cond_broadcast() | 0.003 seconds | 2.628825 |