pthread_cond_broadcast产生的惊群效应和pthread_cond_signal比较

本文通过一个具体的生产者消费者模式实例,探讨了线程间的同步问题,特别是pthread_cond_broadcast与pthread_cond_signal的区别及惊群效应。代码示例展示了如何使用条件变量和互斥锁来实现线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdio.h>
#include <queue>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
using namespace std;

queue<int> res;
pthread_mutex_t mutex;
pthread_cond_t cond;

void *pro(void *sig){
	sleep(3);               //确保所有消费着都能够阻塞到pthread_cond_wait 
	printf("生产这开始进入生产\n");
	pthread_mutex_lock(&mutex);
	res.push(0);
	pthread_mutex_unlock(&mutex);
	pthread_cond_broadcast(&cond);
	printf("生产结束\n");  //直接结束,不在生产,确保消费者只争抢那一个
}

void *cus(void *sig){
	pthread_mutex_lock(&mutex);
	while(res.size()==0){
		printf("cus thread_id is %x 还没有可消费的\n",(unsigned int)pthread_self());
		pthread_cond_wait(&cond,&mutex);
	}
	int i=res.front();
	printf("cus thread_id is %u 消费了 %d\n",(unsigned int)pthread_self(),i);
	res.pop();
	pthread_mutex_unlock(&mutex);
}
int main(){
	pthread_mutex_init(&mutex,NULL);
	pthread_cond_init(&cond,NULL);
	pthread_t q;
	pthread_create(&q,NULL,pro,NULL);
	pthread_t p[3];
	for(int i=0;i<3;i++){
		pthread_create(&p[i],NULL,cus,NULL);
	}


	for(int i=0;i<3;i++){
		pthread_join(p[i],NULL);
	}
	pthread_join(q,NULL);

	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	return 0;
}

只有一个生产者,生产之前先睡眠三秒,以确保所有消费者都在pthead_cond_wait 那里等待,然后生产者只生产一个就推出,确保消费者只争抢那一个

从结果可以看出,一个线程消费后,另外两个线程从先进入循环,打印出信息,可以看出 pthread_cond_broadcast 唤醒了三个消费线程

将pthread_cond_broadcast 换成pthread_cond_signal,结果为

可以看出pthread_cond_signal没有出现惊群效应,我试过超过100个消费者也没有出现,但是从apue对pthread_cond_signal定义上来看:pthread_cond_signal 函数至少能唤醒一个等待该条件的线程,所以也不能排除pthread_cond_signal一定不会出现惊群效应

 

代码只包含我的理解,如果有错误或者我的理解有问题,请各位大佬指出并谅解

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值