【无标题】

c 语言实现生产者消费者
最近捡起来c相关东西顺手写一下多线程相关内容,最经典就是生产者消费者

//
//  test7.c
//  hello_c
//
//  Created by bob on 2026/6/7.
//

#include "test7.h"

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

#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0; //缓冲区当前产品数量

pthread_mutex_t mutex;
pthread_cond_t cont_not_full; //缓冲区不满的信号(通知生产者)
pthread_cond_t cont_not_empty; //缓冲区不空的信号(通知消费者)

void *producer(void*arg){
    for (int i=0; i<BUFFER_SIZE; i++) {
        pthread_mutex_lock(&mutex);
        while (count == BUFFER_SIZE) {
            printf("[生产者] 缓冲区满了,强制休息。。。\n");
            pthread_cond_wait(&cont_not_full, &mutex);
        }
        buffer[count] = i + 1;
        printf("[生产者] 生产了产品 ID: %d (当前库存: %d / %d) \n",buffer[count],count + 1,BUFFER_SIZE);
        count ++;
        
        //生产了东西可以通知消费者处理
        pthread_cond_signal(&cont_not_empty);
        pthread_mutex_unlock(&mutex);
        //生产速度较快 200ms
        usleep(200000);
    }
    return  NULL;
}

void* consumer(void*arg) {
    for (int i=0; i<BUFFER_SIZE; i++) {
        pthread_mutex_lock(&mutex);
        while (count == 0) {
            printf("[消费者] 没货了,嗷嗷待哺中 。。。\n");
            pthread_cond_wait(&cont_not_empty, &mutex);
        }
        count --;
        printf("[消费者] 消费了产品ID: %d,(当前库存: %d / %d ) \n", buffer[count],count,BUFFER_SIZE);
        
        //消费了东西,腾出位置,通知生产者生产继续
        pthread_cond_signal(&cont_not_full);
        pthread_mutex_unlock(&mutex);
        //消费者消费的比较慢 5000ms
        usleep(500000);
    }
    return  NULL;
}

void test7_1() {
    pthread_t prod_tid,cons_tid;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cont_not_full, NULL);
    pthread_cond_init(&cont_not_empty, NULL);
    
    pthread_create(&prod_tid, NULL, producer, NULL);
    pthread_create(&cons_tid, NULL, consumer, NULL);
    
    pthread_join(prod_tid, NULL);
    pthread_join(cons_tid, NULL);
    
    pthread_mutex_destroy(&mutex);
    
    pthread_cond_destroy(&cont_not_full);
    pthread_cond_destroy(&cont_not_empty);
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值