m0_59307035 2021-06-15 01:54 采纳率: 50%
浏览 86
已采纳

生产者和消费者问题操作系统c语言

 

  • 写回答

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;
    }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效