2

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

4

2 回答 2

2

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.

于 2013-09-09T03:22:44.807 回答
1

开放组pthread基本规范指出:

如果当前没有线程阻塞,and 函数将pthread_cond_broadcast()无效。pthread_cond_signal()cond

要衡量这是否需要“仅运行少量的 assmebly [原文如此] 指令”,您必须使用一些运行时性能分析工具(例如 IBM 的 Quantify)并针对您的代码运行它。

于 2013-09-08T13:52:59.423 回答