用c 生产者与消费者问题算法的实现
时间: 2024-05-12 07:15:14 浏览: 20
生产者与消费者问题是一个经典的同步问题,可以使用互斥锁和条件变量来实现。以下是使用C语言编写的生产者与消费者问题算法的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0; // 生产者放置产品的位置
int out = 0; // 消费者取产品的位置
int count = 0; // 缓冲区中的产品数目
pthread_mutex_t mutex; // 互斥锁
pthread_cond_t full; // 缓冲区满条件变量
pthread_cond_t empty; // 缓冲区空条件变量
void *producer(void *arg) {
int i;
for (i = 0; i < 20; i++) {
pthread_mutex_lock(&mutex);
while (count == BUFFER_SIZE) { // 缓冲区满,等待消费者消费
pthread_cond_wait(&full, &mutex);
}
buffer[in] = i;
in = (in + 1) % BUFFER_SIZE;
count++;
printf("Producer produces %d, count=%d\n", i, count);
pthread_cond_signal(&empty); // 通知消费者消费
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
int i, data;
for (i = 0; i < 20; i++) {
pthread_mutex_lock(&mutex);
while (count == 0) { // 缓冲区空,等待生产者生产
pthread_cond_wait(&empty, &mutex);
}
data = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
printf("Consumer consumes %d, count=%d\n", data, count);
pthread_cond_signal(&full); // 通知生产者生产
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t producer_thread, consumer_thread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, 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(&full);
pthread_cond_destroy(&empty);
return 0;
}
```
在这个实现中,生产者线程和消费者线程共享一个缓冲区。当缓冲区已满时,生产者线程等待消费者线程消费产品;当缓冲区为空时,消费者线程等待生产者线程生产产品。使用互斥锁来保证缓冲区的互斥访问,使用条件变量来实现线程间的同步。