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);
}

9076

被折叠的 条评论
为什么被折叠?



