pthread_cond_wait为啥和mutex混在一起?

先复习一下pthread_cond_wait:

int pthread_cond_wait(          pthread_cond_t *cond,          pthread_mutex_t *mutex);

进入这个调用,会unlock传入的mutex,并等待condtion的发生,返回的时候将重新lock mutex

问题来了,这个操作为什么那么妖娆,传入一个mutex,一会unlock,一会lock的?

手册manpage给了说法,转述如下(原文附在后面):

  • 红色句子:很多人看到这个pthread_cond_wait里面带个mutex不是很爽,想把它干掉,但是我们不能这么干,因为现实中就是condition和mutex一起玩

  • 绿色句子:pthread_cond_wait里面带个mutex,虽然怪怪的,但是我们都给你一起打包好了,你只管爽爽的用。这个里面有核心技术:通过调度规则,即考虑了优先权,又兼顾了公平性,能够避免额外上下文切换,保证了信号获取的确定性

  • 蓝色句子:总之,现实情况中,大家就是这么玩的,我们只是把它提炼出来了

Features of Mutexes and Condition Variables

It had been suggested that the mutex acquisition and release be decoupled from condition wait. This was rejected because it is the combined nature of the operation that, in fact, facilitates realtime implementations. Those implementations can atomically move a high-priority thread between the condition variable and the mutex in a manner that is transparent to the caller. This can prevent extra context switches and provide more deterministic acquisition of a mutex when the waiting thread is signaled. Thus, fairness and priority issues can be dealt with directly by the scheduling discipline. Furthermore, the current condition wait operation matches existing practice.

那么也先抛出本文的思考:

  • 如果谁需要开发一个新线程同步的机制,不一定要在conditon wait的操作里面传入一个mutex,比如Linux内核的thread/mutex/semaphore并没有在semaphore的api里面带入一个mutex

  • 那么pthread_cond_wait里面带入一个mutex,这是pthread这个线程库API的设计,之所以这样,是设计者经过考虑发明出来的"最佳"避坑设计(打引号是虽然避坑,但是的确晦涩难懂)

  • 如果使用pthread的这个函数,使用者需要理解它、遵循它,这样不管水平如何,可以很容易的避免一些前人踩过的很多坑

下面是经典的使用模式,不想了解为什么的,可以直接套这个模式即可:

int gx = 0;pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;  pthread_cond_t cond = PTHREAD_COND_INITIALIZER;  // thread Apthread_mutex_lock(&mtx);while (gx == 
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值