2条回答 默认 最新
- CSDN专家-link 2021-06-15 04:43关注
#include <stdio.h> #include <pthread.h> #include <windows.h> #define N 100 #define true 1 #define producerNum 10 #define consumerNum 5 #define sleepTime 1000 typedef int semaphore; typedef int item; item buffer[N] = {0}; int in = 0; int out = 0; int proCount = 0; semaphore mutex = 1, empty = N, full = 0, proCmutex = 1; void * producer(void * a){ while(true){ while(proCmutex <= 0); proCmutex--; proCount++; printf("生产一个产品ID%d, 缓冲区位置为%d\n",proCount,in); proCmutex++; while(empty <= 0){ printf("缓冲区已满!\n"); } empty--; while(mutex <= 0); mutex--; buffer[in] = proCount; in = (in + 1) % N; mutex++; full++; Sleep(sleepTime); } } void * consumer(void *b){ while(true){ while(full <= 0){ printf("缓冲区为空!\n"); } full--; while(mutex <= 0); mutex--; int nextc = buffer[out]; buffer[out] = 0;//消费完将缓冲区设置为0 out = (out + 1) % N; mutex++; empty++; printf("\t\t\t\t消费一个产品ID%d,缓冲区位置为%d\n", nextc,out); Sleep(sleepTime); } } int main() { pthread_t threadPool[producerNum+consumerNum]; int i; for(i = 0; i < producerNum; i++){ pthread_t temp; if(pthread_create(&temp, NULL, producer, NULL) == -1){ printf("ERROR, fail to create producer%d\n", i); exit(1); } threadPool[i] = temp; }//创建生产者进程放入线程池 for(i = 0; i < consumerNum; i++){ pthread_t temp; if(pthread_create(&temp, NULL, consumer, NULL) == -1){ printf("ERROR, fail to create consumer%d\n", i); exit(1); } threadPool[i+producerNum] = temp; }//创建消费者进程放入线程池 void * result; for(i = 0; i < producerNum+consumerNum; i++){ if(pthread_join(threadPool[i], &result) == -1){ printf("fail to recollect\n"); exit(1); } }//运行线程池 return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥100 求数学坐标画圆以及直线的算法
- ¥100 c语言,请帮蒟蒻写一个题的范例作参考
- ¥15 名为“Product”的列已属于此 DataTable
- ¥15 安卓adb backup备份应用数据失败
- ¥15 eclipse运行项目时遇到的问题
- ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
- ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
- ¥15 自己瞎改改,结果现在又运行不了了
- ¥15 链式存储应该如何解决
- ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站