码迷,mamicode.com
首页 > 其他好文 > 详细

c 消费者生产者V2

时间:2020-02-09 16:28:51      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:init   nal   过多   join   生产者   mutex   ons   null   cts   

增加了buffsize,生产者生产过多,wait

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

#define PRODUCER_SIZE 1
#define CONSUMER_SIZE 1

int products = 0;
int buffsize = 5;

pthread_mutex_t mutex;
pthread_cond_t empty_cond;
pthread_cond_t full_cond;

void produce();
void consume();


int main() {
    pthread_t producer;
    pthread_t consumer;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&empty_cond, NULL);
    pthread_cond_init(&full_cond, NULL);

    pthread_create(&producer, NULL, produce, NULL);
    pthread_create(&consumer, NULL, consume, NULL);

    pthread_join(producer, NULL);
    pthread_join(consumer, NULL);

    return 0;
}

void produce(){
//    sleep(2);
    printf("start produce\n");
    while (1) {
        pthread_mutex_lock(&mutex);
        while (products >= 10) {
            printf("buff full, producer start wait\n");
            pthread_cond_wait(&full_cond, &mutex);
            printf("producer wakeup\n");
        }
        products++;
        printf("produce:%d start wake consum\n", products);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&empty_cond);
        sleep(1);
    }
}

void consume() {
    printf("start consum\n");
    while (1) {
        pthread_mutex_lock(&mutex);
        while (products <= buffsize) {
            printf("consum start wait cond\n");
            pthread_cond_wait(&empty_cond, &mutex);
            printf("consum wake up\n");
        }
        if (products > 0) {
            printf("consum:%d\n", products);
            products --;
        }
        pthread_cond_signal(&full_cond);
        pthread_mutex_unlock(&mutex);
        sleep(3);
    }
}

  

c 消费者生产者V2

标签:init   nal   过多   join   生产者   mutex   ons   null   cts   

原文地址:https://www.cnblogs.com/luckygxf/p/12287148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!