首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

准确使用pthread_cond_wait

2012-07-01 
正确使用pthread_cond_wait消费者的两种等待方式:方式1:?if (empty(queue)) {? ? pthread_cond_wait(&queu

正确使用pthread_cond_wait

消费者的两种等待方式:

方式1:?

if (empty(queue)) {

? ? pthread_cond_wait(&queue_has_element, &mutex);

}

element = dequeue(queue);


方式2:

while (empty(queue)) {

? ? pthread_cond_wait(&queue_has_element, &mutex);

}

element = dequeue(queue);


说明:

方式1的等待存在问题, 如果多个消费者都在等待queue_has_element, 此时, 生产者产生

一个元素, 并调用pthread_cond_broadcast把所有消费者都惊醒, 而元素确只有一个, 这

意味着只有一个消费者可以得到这个元素, 其余消费者应该继续等. 但是方式1. 所有消费者

不等待, 去一个空队列取元素将会发生错误. 方式2是正确的处理方式. 每个消费者醒了之后,

还会检查一次队列,?如果队列依然为空, 则继续等待...?


PS: 如果使用pthread_cond_broadcast来广播信号, 条件变量满足后, 不一定真的代表资

源满足.?只有在使用pthread_cond_signal的情况下, 条件变量的满足才意味着资源也满足.

?

?

热点排行