博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
pthread_cond_signal惊群现象
阅读量:4648 次
发布时间:2019-06-09

本文共 2422 字,大约阅读时间需要 8 分钟。

1.如下代码所示:

#include 
#include
#include
#include
pthread_mutex_t count_lock;pthread_cond_t count_ready;int count;void *decrement_count(void *arg){ while(1) { pthread_mutex_lock(&count_lock); printf("decrement:waiting\n"); /*等待满足条件,期间互斥量仍然可用*/ // while (count == 0) pthread_cond_wait(&count_ready, &count_lock); printf("decrement:count = %d\n", count); if (count == 0) { printf("exit count:%d\n",count); exit(1); } count = 0; pthread_mutex_unlock(&count_lock); } pthread_exit(NULL);}void *increment_count(void *arg){ while(1) { pthread_mutex_lock(&count_lock);// printf("increment:running\n"); count = 1; /*通知线程条件已满足*/// printf("increment:count = %d\n", count); pthread_cond_signal(&count_ready); pthread_mutex_unlock(&count_lock); } pthread_exit(NULL);}int main(){ pthread_t tid1,tid2,tid3; count=0; pthread_mutex_init(&count_lock, NULL); pthread_cond_init(&count_ready, NULL); pthread_create(&tid1, NULL, decrement_count, NULL); sleep(3); pthread_create(&tid3, NULL, decrement_count, NULL); sleep(3); pthread_create(&tid2, NULL, increment_count, NULL); /*等待decrement退出*/ pthread_join(tid2, NULL); printf("decrement quit\n"); pthread_join(tid3, NULL); pthread_join(tid1, NULL); return 0;}

g++ -g thread-cond.cpp -lpthread -o test 编译出test程序。

然后运行,可见程序

decrement:waiting

decrement:waiting
decrement:count = 1
decrement:waiting
decrement:count = 0
exit count:0

最后退出了,为什么?

如果把tid1,tid2,tid3表示为每个线程获得互斥锁,那么这种情况的发生说明tid1和tid3顺序获得锁执行了(顺序也可能为tid3和tid1).

单从pthread_cond_signal函数的定义上看,如果严格的只发一个"信号"给指定一个线程,这种情况是绝对不可能发生的。

因为函数中pthread_cond_wait的返回代表了此线程接受到“信号”(pthread_cond_wait执行包括1.解锁2.wait3.获得锁4.返回)

只有一个原因能解释:pthread_cond_signal一次唤醒了2个wait线程,第1个获得锁的线程把count置为0,第2个线程发现count=0直接exit,

pthread_cond_signal发生了惊群现象。

怎么预防:

while (count == 0)          pthread_cond_wait(&count_ready, &count_lock); 在wait返回后加一个while来判断“条件”是否满足要求。

 

转载于:https://www.cnblogs.com/dodng/p/4380035.html

你可能感兴趣的文章
JS面向对象的实现和原理
查看>>
Linux系统中常用操作命令
查看>>
针对模拟滚动条插件(jQuery.slimscroll.js)的修改
查看>>
poi实现excel数据导入数据库
查看>>
实验七
查看>>
Linux高级编程(四)
查看>>
python pandas 对带时间序列的数据进行重采样处理
查看>>
7,7显示选中的目标信息
查看>>
DELPHI TreeView 文件目录树和 设置节点图标 完整
查看>>
安卓教程:提取APK程序里图片资源的方法
查看>>
[置顶] Android adb root权限
查看>>
单个雪碧图多个图像资源你该如何解决它们的定位?
查看>>
python 3.6 MJ小工具
查看>>
个人看法---团队合作
查看>>
jvm垃圾回收
查看>>
数据库索引
查看>>
poj 1466 Girls and Boys (最大独立集)
查看>>
MYSQL-交换表中2行2字段的值
查看>>
GNU-Radio & USRP Example
查看>>
TensorFlow函数(十)tf.global_variables_initializer()
查看>>