生产者-消费者进程的同步与互斥c语言实现
时间: 2023-10-10 09:15:44 浏览: 165
生产者与消费者 进程的同步与互斥模拟
5星 · 资源好评率100%
生产者-消费者问题是一个经典的同步问题,涉及到两个进程之间的协作和互斥,下面是一个使用互斥锁和条件变量实现的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
void *producer(void *arg) {
int item;
while (1) {
item = rand();
pthread_mutex_lock(&mutex);
while ((in + 1) % BUFFER_SIZE == out) {
pthread_cond_wait(&empty, &mutex);
}
buffer[in] = item;
printf("producer produced item %d\n", item);
in = (in + 1) % BUFFER_SIZE;
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consumer(void *arg) {
int item;
while (1) {
pthread_mutex_lock(&mutex);
while (in == out) {
pthread_cond_wait(&full, &mutex);
}
item = buffer[out];
printf("consumer consumed item %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&empty, NULL);
pthread_cond_init(&full, NULL);
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);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&empty);
pthread_cond_destroy(&full);
return 0;
}
```
在这个示例中,我们使用了互斥锁和条件变量,分别实现了互斥和缓冲区空和缓冲区满两个条件。当生产者生产一个物品时,它需要先获取互斥锁(mutex),检查缓冲区是否已满,如果已满则等待缓冲区不满(empty条件变量),然后将物品放入缓冲区,更新in指针,通知消费者缓冲区不为空(full条件变量),最后释放互斥锁。消费者在消费物品之前需要获取互斥锁(mutex),检查缓冲区是否为空,如果为空则等待缓冲区不为空(full条件变量),从缓冲区中取出物品,更新out指针,通知生产者缓冲区不满(empty条件变量),最后释放互斥锁。
这个示例中使用了pthread库中的线程,如果你不熟悉线程的概念,可以先学习一下线程的基本知识。
阅读全文