美文网首页
生产者消费者问题模拟(Linux C)

生产者消费者问题模拟(Linux C)

作者: blackOak | 来源:发表于2019-02-04 20:48 被阅读0次

    题目

    3个生产者,2个消费者
    库存大小为10
    生产者共享一个变量产品编号productID,每生产一个产品,productID加1,不能出现重复编号
    每个生产者每生产一个产品,打印出生产者的进程/线程标识符信息,以及生产的产品编号信息
    生产者生产一个产品后,休眠2ms
    消费者每消费一个产品,打印出消费者的进程/线程标识符信息,以及消费的产品编号信息
    消费者消费一个产品后,休眠3ms

    代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <ctype.h>
    #include <semaphore.h>
    #include <unistd.h>
    #define N 10
    
    int buf[N];
    sem_t empty, full, pmutex, cmutex;
    int productID = 0;
    int in = 0, out = 0;
    
    void *producer(void *arg);
    void *consumer(void *arg);
    
    int main()
    {
        sem_init(&empty, 0, N);
        sem_init(&full, 0, 0);
        sem_init(&pmutex, 0, 1);
        sem_init(&cmutex, 0, 1);
    
        pthread_t pro1, pro2, pro3;
        pthread_t con1, con2;
        pthread_create(&pro1, NULL, producer, &pro1);
        pthread_create(&pro2, NULL, producer, &pro2);
        pthread_create(&pro3, NULL, producer, &pro3);
        pthread_create(&con1, NULL, consumer, &con1);
        pthread_create(&con2, NULL, consumer, &con2);
        pthread_join(pro1, NULL);
        pthread_join(pro2, NULL);
        pthread_join(pro3, NULL);
        pthread_join(con1, NULL);
        pthread_join(con2, NULL);
    
        sem_destroy(&empty);
        sem_destroy(&full);
        sem_destroy(&pmutex);
        sem_destroy(&cmutex);
        return 0;
    }
    
    void* producer(void *arg)//限制循环10次
    {
        pthread_t *tid = (pthread_t *)arg;
        int i = 0;
        while(i < 10)
        {
            sem_wait(&empty);
            sem_wait(&pmutex);
            productID++;
            buf[in] = productID;
            in = (in+1)%N;
            printf("%s%ld\t%s%d\n", "tid  ", *tid, "生产:", productID);
            sem_post(&pmutex);
            sem_post(&full);
            sleep(0.002);
            i++;
        }
        return NULL;
    }
    
    void* consumer(void *arg)
    {
        pthread_t *tid = (pthread_t *)arg;
        int i = 0;
        while(i < 10)
        {
            sem_wait(&full);
            sem_wait(&cmutex);
            printf("%s%ld\t%s%d\n", "tid  ", *tid, "消费:", buf[out]);
            out = (out+1)%N;
            sem_post(&cmutex);
            sem_post(&empty);
            sleep(0.003);
            i++;
        }
        return NULL;
    }
    

    相关文章

      网友评论

          本文标题:生产者消费者问题模拟(Linux C)

          本文链接:https://www.haomeiwen.com/subject/idqmsqtx.html