c语言生产者消费者问题
时间: 2023-08-24 12:30:19 浏览: 39
生产者消费者问题是多线程编程中经典的同步问题,主要是解决生产者和消费者在共享资源时的同步与互斥问题。在C语言中,可以通过使用互斥锁和条件变量来实现生产者消费者问题的解决方案。以下是一个简单的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *producer(void *arg){
int i = 0;
while(1){
pthread_mutex_lock(&mutex);
if(count == BUFFER_SIZE){
pthread_cond_wait(&cond, &mutex);
}
buffer[count] = i;
count++;
printf("producer produce %d\n", i);
i++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
}
void *consumer(void *arg){
while(1){
pthread_mutex_lock(&mutex);
if(count == 0){
pthread_cond_wait(&cond, &mutex);
}
int data = buffer[count-1];
count--;
printf("consumer consume %d\n", data);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
}
int main(){
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
```
在这个示例中,我们使用互斥锁mutex和条件变量cond来解决生产者消费者问题。生产者线程不断地往buffer数组中添加数据,如果buffer数组已满,则等待条件变量cond的信号。消费者线程不断地从buffer数组中取出数据,如果buffer数组为空,则等待条件变量cond的信号。每次生产者添加数据或消费者取出数据时,都需要发送条件变量cond的信号,以唤醒等待在条件变量cond上的线程。