分布式选修课上讲了多线程编程,布置了一个生产者消费者的作业,觉得挺有意思,并且网络上的消费者问题多使用c语言编写,故在此记录c++解决方法
由于是消费者线程各自计数,故使用一个全局数组变量存储各线程的结果,最后在主函数求和,主要结构及解释如下
完整代码如下
#include<iostream>
#include<pthread.h>
using namespace std;
int ans[100];
pthread_mutex_t count_mutex;
pthread_cond_t condc;
pthread_cond_t condp;
int store[11]; //定义缓冲区,store[0]代表空,不使用
int flag = 0; //栈标记
int consum = 1; //记录消费数量
struct sum_data //记录是第几个消费者线程
{
int number;
};
void *consumer(void *threadarg) //消费者
{
struct sum_data *my_data;
my_data = (struct sum_data *) threadarg;
int s = 0;
while(1)
{
pthread_mutex_lock(&count_mutex);
while(flag == 0 &&am