生产者消费者代码c语言
时间: 2024-10-24 13:01:42 浏览: 35
生产者消费者问题是经典的并发编程示例,它涉及到两个角色:生产者和消费者。在C语言中,可以使用互斥量(mutex)、条件变量(condition variables)或信号量(semaphores)等同步原语来解决这个问题。以下是简单的基于互斥量和缓冲区的生产者消费者模型:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int count = 0;
int inuse = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_empty = PTHREAD_COND_INITIALIZER;
void* producer(void* arg) {
int value = 1;
while (1) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) { // 如果缓冲区满
pthread_cond_wait(&cond_full, &mutex); // 等待条件
}
buffer[count++] = value; // 生产数据并更新计数
printf("Producer produced %d\n", value++);
pthread_mutex_unlock(&mutex);
if (count >= BUFFER_SIZE) {
pthread_cond_signal(&cond_empty); // 队列满,唤醒消费者
}
}
return NULL;
}
void* consumer(void* arg) {
while (1) {
pthread_mutex_lock(&mutex);
while (count == 0) { // 如果缓冲区空
pthread_cond_wait(&cond_empty, &mutex); // 等待条件
}
int data = buffer[--count]; // 消费数据并更新计数
printf("Consumer consumed %d\n", data);
pthread_mutex_unlock(&mutex);
if (count == 0) {
pthread_cond_signal(&cond_full); // 队列空,唤醒生产者
}
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
return 0;
}
```
在这个例子中,`producer`线程负责向缓冲区添加数据,`consumer`线程则从缓冲区取出数据。通过互斥锁保证了同时只有一个线程能访问缓冲区,而条件变量则让线程在必要时进入等待状态。
阅读全文