zoukankan      html  css  js  c++  java
  • c 生产者消费者V1

    1. 生产者1个线程

    2. 消费者1个线程

    3. 通过pthread_mutex_t并发控制

    4. 通过pthread_cond_t wait signal

    5. signal放到unlock后面

    6. sleep放到unlock后面

    #include <stdio.h>
    #include <unistd.h>
    #include <pthread.h>
    
    #define PRODUCER_SIZE 1
    #define CONSUMER_SIZE 1
    
    int products = 0;
    
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    
    void produce();
    void consume();
    
    
    int main() {
        pthread_t producer;
        pthread_t consumer;
    
        pthread_mutex_init(&mutex, NULL);
        pthread_cond_init(&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);
            products++;
            printf("produce:%d start wake consum
    ", products);
            pthread_mutex_unlock(&mutex);
            pthread_cond_signal(&cond);
            sleep(1);
        }
    }
    
    void consume() {
        printf("start consum
    ");
        while (1) {
            pthread_mutex_lock(&mutex);
            while (products <= 0) {
                printf("consum start wait cond
    ");
                pthread_cond_wait(&cond, &mutex);
                printf("consum wake up
    ");
            }
            if (products > 0) {
                printf("consum:%d
    ", products);
                products --;
            }
            pthread_mutex_unlock(&mutex);
            sleep(3);
        }
    }
    

      

  • 相关阅读:
    二 .数据库(Data)操作
    一. 数据库(Data)基础
    五种IO/模型
    并发编程 (协程)
    七.并发编程 (线程池,返回值,回调函数)
    六.并发编程 (线程对列)
    五.并发编程 (线程事件)
    四.并发编程 (线程信号量)
    三.并发编程 (线程锁)
    二.并发编程 (程序中线程操作)
  • 原文地址:https://www.cnblogs.com/luckygxf/p/12287121.html
Copyright © 2011-2022 走看看