#include <stdio.h> #include <semaphore.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define N1 3//定义3个生产者 #define N2 4//定义4 个消费者 #define M 10//定义10个大小缓冲区 int in = 0; int out = 0; int buff[M] = {0};//缓冲区大小为10 sem_t empty_sem;//空缓冲区数量 sem_t full_sem;//满缓冲区数量 pthread_mutex_t mutex;//互斥访问缓冲区 int product_id = 0; int consumer_id = 0; int data; FILE *fp; void * product() { int id = ++product_id; while(1) { sleep(1); sem_wait(&empty_sem); pthread_mutex_lock(&mutex); //if(feof(fp) != 0) fseek(fp, 0, SEEK_SET); if(fscanf(fp, "%d", &data)==EOF) { fseek(fp, 0, SEEK_SET); fscanf(fp, "%d", &data); } in = in % M; buff[in] = data; printf("Producter %d produce %d in position %d ", id, buff[in], in); ++in; pthread_mutex_unlock(&mutex); sem_post(&full_sem); } } void *consume() { int id = ++consumer_id; while(1) { sleep(1); sem_wait(&full_sem); pthread_mutex_lock(&mutex); out = out % M; printf("Consumer %d take product %d in position %d ", id, buff[out], out); buff[out] = 0; ++out; pthread_mutex_unlock(&mutex); sem_post(&empty_sem); } } int main() { pthread_t id1[N1];//定义生产者线程 pthread_t id2[N2];//定义消费者线程 int i; int ret1[N1]; int ret2[N2]; int ini1 = sem_init(&empty_sem, 0, M); //初始化空缓冲区 为 M(10) int ini2 = sem_init(&full_sem, 0, 0);//初始化满缓冲区 0 if(ini1 && ini2 != 0) { printf("Sem init failed "); exit(1); } int ini3 = pthread_mutex_init(&mutex, NULL);//初始化互斥信号量 if(ini3 != 0 ) { printf("mutex init failed "); exit(1); } fp = fopen("/.data.txt", "r");//打开文件Data.txt if(fp == NULL) exit(1); for(i = 0; i < N1; i++) { ret1[i] = pthread_create(&id1[i], NULL, product, (void*)(&i));//创建生产者线程 if(ret1[i] != 0) { printf("product%d creat failed ", i); exit(1); } } for(i = 0; i< N2; i++) { ret2[i] = pthread_create(&id2[i], NULL, consume, NULL);//创建消费者线程 if(ret2[i] != 0) { printf("consumer%d creat failed ", i); exit(1); } } for(i = 0; i < N1; i++) {pthread_join(id1[i], NULL);} for(i = 0; i < N2; i++) {pthread_join(id2[i], NULL);} exit(0); }