Search code examples
linuxperformancepthreadscondition-variablenptl

performance of pthread_cond_broadcast when no one is waiting on condition


If I call pthread_cond_broadcast and no one is waiting on the condition, will the pthread_cond_broadcast invoke a context switch and/or call to kernel?

If not, can I rely on it being very fast (by fast I mean, just running a small number of assmebly instruction in current process and then returning)?


Solution

  • There are no guarantees in POSIX, but since your question is tagged linux and nptl an answer in that context can be given.

    If there are no waiters on the condition variable, then the nptl glibc code for pthread_cond_broadcast() just takes a low-level lock protecting the internals of the condition variable itself, tests a value then unlocks the low-level lock. The low-level lock itself uses a futex, which will only enter the kernel if there is contention on that lock.

    This means that unless there is a lot of contention on the condition variable itself (ie. a large number of threads frequently calling pthread_cond_broadcast() / pthread_cond_signal() on the same condition variable) there will be no system call to the kernel, and the overhead will only be a few locked instructions.