http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/
pthread_mutex_lock(&mutex);
predicate=true;
pthread_cond_signal(&cv); // OR: pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex); // : pthread_cond_signal(&cv);
Signal with Mutex Locked
On some platforms, the OS performs a context switch to the woken thread right after the signal/broadcast operation, to minimize latency. On a single processor system, this may lead to unnecessary context switches if we signal or broadcast while holding the mutex.

Indeed, consider the scenario shown in figure 1. The thread T2 is blocked on the condition variable. T1 signals the condition while holding the associated mutex. A context switch to T2 occurs and T2 wakes up. But before returning frompthread_cond_wait, T2 needs to lock the mutex. However that mutex is already hold by T1. As a result T2 blocks (but this time contends for the mutex) and a context switch to T1 occurs. Then T1 unlocks the mutex, and T2 becomes finally runnable. The situation appears to be even worse, if we broadcast the condition variable to several threads.
本文探讨了在某些平台上,当使用pthread条件变量时,如果在发送信号时保持互斥锁锁定可能会导致不必要的上下文切换。这种情况尤其发生在单处理器系统中。文章通过一个示例场景说明了这一问题,并解释了为什么这种做法可能导致额外的开销。
848

被折叠的 条评论
为什么被折叠?



