进程同步与互斥生产者消费者c语言代码
时间: 2023-07-31 14:08:32 浏览: 43
下面是一个使用信号量实现进程同步与互斥的生产者消费者问题的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10 // 缓冲区大小
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0; // 缓冲区写指针
int out = 0; // 缓冲区读指针
sem_t empty; // 空缓冲区信号量
sem_t full; // 满缓冲区信号量
sem_t mutex; // 互斥信号量
void *producer(void *arg);
void *consumer(void *arg);
int main(int argc, char *argv[]) {
pthread_t producer_thread, consumer_thread;
// 初始化信号量
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
// 创建生产者线程和消费者线程
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// 等待线程结束
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// 销毁信号量
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
void *producer(void *arg) {
int item;
while (1) {
item = rand() % 100; // 随机生成一个生产的产品
sem_wait(&empty); // 等待空缓冲区
sem_wait(&mutex); // 互斥访问缓冲区
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
printf("Producer produced item %d\n", item);
sem_post(&mutex); // 释放互斥信号量
sem_post(&full); // 发送满缓冲区信号量
}
}
void *consumer(void *arg) {
int item;
while (1) {
sem_wait(&full); // 等待满缓冲区
sem_wait(&mutex); // 互斥访问缓冲区
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
printf("Consumer consumed item %d\n", item);
sem_post(&mutex); // 释放互斥信号量
sem_post(&empty); // 发送空缓冲区信号量
}
}
```
上述代码中,我们使用了三个信号量 `empty`、`full` 和 `mutex` 分别表示空缓冲区、满缓冲区和互斥访问缓冲区的状态。生产者和消费者在访问缓冲区时,都需要先获取互斥信号量 `mutex`,以确保同一时刻只有一个进程在访问缓冲区。生产者在向缓冲区写入数据时,需要等待 `empty` 信号量,以确保缓冲区有空闲位置;写入完成后,需要释放 `full` 信号量,通知消费者缓冲区有数据可供消费。消费者在从缓冲区读取数据时,需要等待 `full` 信号量,以确保缓冲区有数据可供读取;读取完成后,需要释放 `empty` 信号量,通知生产者缓冲区有空闲位置。