Domanda

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)?

È stato utile?

Soluzione

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.

Altri suggerimenti

The pthread Open Group Base Specifications states:

The pthread_cond_broadcast() and pthread_cond_signal() functions shall have no effect if there are no threads currently blocked on cond.

To get a measure of whether or not this takes "just running a small number of assmebly [sic] instruction" you'll have to get out some run-time performance-analysis tool (e.g IBM's Quantify) and run it against your code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top