• c 消费者生产者V2


    增加了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
    ");
        while (1) {
            pthread_mutex_lock(&mutex);
            while (products >= 10) {
                printf("buff full, producer start wait
    ");
                pthread_cond_wait(&full_cond, &mutex);
                printf("producer wakeup
    ");
            }
            products++;
            printf("produce:%d start wake consum
    ", products);
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&empty_cond);
            sleep(1);
        }
    }
    
    void consume() {
        printf("start consum
    ");
        while (1) {
            pthread_mutex_lock(&mutex);
            while (products <= buffsize) {
                printf("consum start wait cond
    ");
                pthread_cond_wait(&empty_cond, &mutex);
                printf("consum wake up
    ");
            }
            if (products > 0) {
                printf("consum:%d
    ", products);
                products --;
            }
            pthread_cond_signal(&full_cond);
            pthread_mutex_unlock(&mutex);
            sleep(3);
        }
    }
    

      

  • 相关阅读:
    大数据概述 106
    编译原理学习随笔 106
    我与ruby第一次接触
    xml在joomla表单中的应用详解
    joomla2.5传统组件开发解析
    joomla2.5开发系列教程原创(1)2.5与1.5异同点
    CSS2简写和常用css总结笔记
    C语言开发php扩展链接库初学
    ruby转战Ubuntu,真折腾?
    joomla搜索功能开发和结果分页探讨
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12287148.html
Copyright © 2020-2023  润新知