weichuang02 发表于 2012-08-19 18:36

[结贴]pthread为什么规定cond要和mutex一起使用?

本帖最后由 weichuang02 于 2013-06-05 11:25 编辑

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

DESCRIPTION
       A condition (short for ``condition variable'') is a synchronization device that allows threadstosuspendexecutionand
       relinquishthe 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 untilanother
       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呢?

谢谢指点!

weichuang02 发表于 2012-08-19 19:02

我想问的是,pthread_cond这样设计的原因是什么?

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

希望我说明白了。谢谢。

_Rayx 发表于 2012-08-20 09:18

条件变量是由互斥变量保护的,锁住互斥变量后才能计算条件。

weichuang02 发表于 2012-08-20 20:41

_Rayx 发表于 2012-08-20 09:18 static/image/common/back.gif
条件变量是由互斥变量保护的,锁住互斥变量后才能计算条件。

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

incle 发表于 2012-08-21 17:47

同问.....:lol

Moon_Bird 发表于 2012-08-21 19:34

回复 4# weichuang02

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

a174787252 发表于 2013-06-03 08:53

回复 4# weichuang02


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

gulang2004xy 发表于 2013-06-03 14:04

http://www.cnblogs.com/lonelycatcher/archive/2011/12/20/2294161.html
这个讲的非常好。建议看一下!

superwiles 发表于 2013-06-11 00:37

看看LPI,解释的非常清楚了
页: [1]
查看完整版本: [结贴]pthread为什么规定cond要和mutex一起使用?