免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 6942 | 回复: 8
打印 上一主题 下一主题

[Linux] [结贴]pthread为什么规定cond要和mutex一起使用? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-08-19 18:36 |只看该作者 |倒序浏览
本帖最后由 weichuang02 于 2013-06-05 11:25 编辑

man phread_cond出来的内容是这样的:

DESCRIPTION
       A condition (short for ``condition variable'') is a synchronization device that allows threads  to  suspend  execution  and
       relinquish  the processors until some predicate on shared data is satisfied. The basic operations on conditions are: signal
       the condition (when the predicate becomes true), and wait for the condition, suspending the thread execution until  another
       thread signals the condition.

      A condition variable must always be associated with a mutex, to avoid the race condition where a thread prepares to wait on
       a condition variable and another thread signals the condition just before the first thread actually waits on it.

想不通的一点是,既然已经有了pthread_mutex_lock这样的线程锁,那么pthread_cond看起来有点像windodws平台的Event概念,就是一个事件通知的句柄。
但是windows平台的mutex和event是相互独立的,并没有规定event要和mutex一起用。那么为什么pthread要规定 A condition variable must always be associated with a mutex呢?

谢谢指点!

论坛徽章:
0
2 [报告]
发表于 2012-08-19 19:02 |只看该作者
我想问的是,pthread_cond这样设计的原因是什么?

是这样的,我以前在windows平台开发,WaitForSingleObject函数的参数或者是event或者是mutex. 为什么posix要在pthread函数里面,用一个cond去wait一个mutex,干嘛要同时操作两个资源呢? windows上的只用操作一个资源就可以了。

希望我说明白了。谢谢。

论坛徽章:
0
3 [报告]
发表于 2012-08-20 09:18 |只看该作者
条件变量是由互斥变量保护的,锁住互斥变量后才能计算条件。

论坛徽章:
0
4 [报告]
发表于 2012-08-20 20:41 |只看该作者
_Rayx 发表于 2012-08-20 09:18
条件变量是由互斥变量保护的,锁住互斥变量后才能计算条件。


问题是,互斥是两个线程之间的。如果我要一个线程signal,多个线程同时wait被唤醒,怎么办呢? mutex的语义似乎不支持啊。

论坛徽章:
24
15-16赛季CBA联赛之北京
日期:2018-08-17 18:43:33技术图书徽章
日期:2018-08-22 12:53:57技术图书徽章
日期:2018-08-22 12:54:20技术图书徽章
日期:2018-08-22 12:54:3015-16赛季CBA联赛之福建
日期:2018-10-19 16:58:1619周年集字徽章-庆
日期:2019-08-27 13:28:5619周年集字徽章-19
日期:2019-08-27 13:31:2619周年集字徽章-19
日期:2019-08-27 13:31:2615-16赛季CBA联赛之同曦
日期:2019-09-05 12:03:2819周年集字徽章-周
日期:2019-09-06 18:54:5415-16赛季CBA联赛之上海
日期:2018-07-25 11:55:2615-16赛季CBA联赛之青岛
日期:2018-07-10 14:13:18
5 [报告]
发表于 2012-08-21 17:47 |只看该作者
同问.....

论坛徽章:
0
6 [报告]
发表于 2012-08-21 19:34 |只看该作者
回复 4# weichuang02

在 pthread_cond_wait 里面有一个解锁后进入睡眠  唤醒后再加锁的操作,这样做的意义在于 线程在进入等待信号进入休眠之前 不会错过条件信号
singal 只能唤醒单个线程 , 唤醒多个用 pthread_cond_broadcast.
   

论坛徽章:
0
7 [报告]
发表于 2013-06-03 08:53 |只看该作者
回复 4# weichuang02


    你自己已经解决你的问题了 ,对于对于不同的等待线程,他们监听的&mutex 是不一样的。所以只唤醒我们关注的线程。

论坛徽章:
0
8 [报告]
发表于 2013-06-03 14:04 |只看该作者
http://www.cnblogs.com/lonelycat ... /12/20/2294161.html
这个讲的非常好。建议看一下!

论坛徽章:
0
9 [报告]
发表于 2013-06-11 00:37 |只看该作者
看看LPI,解释的非常清楚了
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP