2010-10-31 86 views

回答

17

是的。如果你有单独的条件你想等待,这有时是一个好主意。例如,你可能有一个队列和条件变量,用于“不满”和“不为空”等等......有人将数据放在队列中等待“不满”。有人从队列中取数据等待“不空”。他们都使用相同的互斥量。

+0

非常感谢。任何相关链接? – Fanatic23 2010-10-31 06:55:05

+0

谷歌这个例子:http://cs.wmich.edu/~jjwillia/10.spring/cs4540/asgn2/pthreads-pro-con – xscott 2010-10-31 06:57:30

+0

很晚评论,但使用2个condvars与一个互斥实际上是建议的做法例如排队情况,请参阅Butenhof'使用Posix线程编程'。 – 2017-02-24 08:40:49

21

是的。这是常见的初步实践:

典型的例子:

mutex queue_mutex; 
cond queue_is_not_full_cond; 
cond queue_is_not_empty_cond; 

push() 
    lock(queue_mutex) 
     while(queue is full) 
     wait(queue_is_not_full_cond,queue_mutex); 
     do push... 
     signal(queue_is_not_empty_cond) 
    unlock(queue_mutex) 

pop() 
    lock(queue_mutex) 
     while(queue is empty) 
     wait(queue_is_not_empty_cond,queue_mutex); 
     do pop... 
     signal(queue_is_not_full_cond) 
    unlock(queue_mutex) 
+1

+1代表伪码 – Fanatic23 2010-10-31 07:06:07