#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一定不会出现惊群效应
代码只包含我的理解,如果有错误或者我的理解有问题,请各位大佬指出并谅解