pthread_cond_wait与signal

本文探讨了在某些平台上,当使用pthread条件变量时,如果在发送信号时保持互斥锁锁定可能会导致不必要的上下文切换。这种情况尤其发生在单处理器系统中。文章通过一个示例场景说明了这一问题,并解释了为什么这种做法可能导致额外的开销。

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.

signal with mutex locked

Fig 1- signal with mutex locked. We get 2 unnecessary context switch.

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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值