C语言编写一个生产者和消费者程序
时间: 2024-10-10 21:02:14 浏览: 51
在C语言中,生产者和消费者是一种经典的并发编程模型,它通常使用互斥量(mutex)和条件变量(condition variable)来控制两个线程之间的交互。这里是一个简单的例子,假设我们有一个共享缓冲区,生产者负责生产数据放入缓冲区,消费者则从缓冲区中取出数据消费。
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
#define MAX_ITEMS 50
typedef struct {
int buffer[BUFFER_SIZE];
int count;
int max_count;
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t cond; // 条件变量
} producer_consumer;
void* producer(void* arg) {
producer_consumer* pc = (producer_consumer*)arg;
for (int i = 0; i < MAX_ITEMS; ++i) {
pthread_mutex_lock(&pc->mutex);
while (pc->count == pc->max_count) {
pthread_cond_wait(&pc->cond, &pc->mutex); // 等待唤醒
}
pc->buffer[pc->count++] = i;
printf("Produced item %d\n", i);
if (pc->count == pc->max_count) {
printf("Buffer full, stopping producer.\n");
break;
}
pthread_mutex_unlock(&pc->mutex);
}
pthread_exit(NULL);
}
void* consumer(void* arg) {
producer_consumer* pc = (producer_consumer*)arg;
for (int i = 0; i < MAX_ITEMS; ++i) {
pthread_mutex_lock(&pc->mutex);
while (pc->count == 0) {
pthread_cond_wait(&pc->cond, &pc->mutex); // 等待唤醒
}
pc->count--;
printf("Consumed item %d\n", pc->buffer[i]);
if (pc->count == 0) {
printf("Buffer empty, stopping consumer.\n");
break;
}
pthread_mutex_unlock(&pc->mutex);
}
pthread_exit(NULL);
}
int main() {
producer_consumer pc;
pthread_t producer_thread, consumer_thread;
int ret;
// 初始化互斥锁和条件变量
pthread_mutex_init(&pc.mutex, NULL);
pthread_cond_init(&pc.cond, NULL);
// 设置缓冲区大小和最大元素数
pc.max_count = BUFFER_SIZE;
// 创建并启动生产者和消费者线程
ret = pthread_create(&producer_thread, NULL, producer, &pc);
if (ret != 0) {
perror("Producer thread creation failed");
return -1;
}
ret = pthread_create(&consumer_thread, NULL, consumer, &pc);
if (ret != 0) {
perror("Consumer thread creation failed");
return -1;
}
// 等待线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// 清理资源
pthread_mutex_destroy(&pc.mutex);
pthread_cond_destroy(&pc.cond);
return 0;
}
```
阅读全文
相关推荐


















