c语言代码实现操作系统生产者消费者问题实现循环利用缓冲区
时间: 2024-05-12 16:19:04 浏览: 95
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5 // 缓冲区大小
#define PRODUCER_NUM 2 // 生产者数量
#define CONSUMER_NUM 2 // 消费者数量
sem_t empty; // 空缓冲区信号量
sem_t full; // 满缓冲区信号量
sem_t mutex; // 互斥信号量
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0; // 生产者写入位置
int out = 0; // 消费者读取位置
void *producer(void *arg) {
int i, item;
while (1) {
item = rand() % 100; // 生产一个随机数
sem_wait(&empty); // 等待空缓冲区
sem_wait(&mutex); // 等待互斥信号量
buffer[in] = item; // 将数据写入缓冲区
printf("Producer %d produced item %d at position %d\n", *(int *)arg, item, in);
in = (in + 1) % BUFFER_SIZE; // 更新写入位置
sem_post(&mutex); // 释放互斥信号量
sem_post(&full); // 发送满缓冲区信号
sleep(rand() % 3); // 等待随机时间
}
}
void *consumer(void *arg) {
int i, item;
while (1) {
sem_wait(&full); // 等待满缓冲区
sem_wait(&mutex); // 等待互斥信号量
item = buffer[out]; // 从缓冲区读取数据
printf("Consumer %d consumed item %d at position %d\n", *(int *)arg, item, out);
out = (out + 1) % BUFFER_SIZE; // 更新读取位置
sem_post(&mutex); // 释放互斥信号量
sem_post(&empty); // 发送空缓冲区信号
sleep(rand() % 3); // 等待随机时间
}
}
int main() {
int i;
pthread_t producers[PRODUCER_NUM];
pthread_t consumers[CONSUMER_NUM];
int producer_args[PRODUCER_NUM];
int consumer_args[CONSUMER_NUM];
// 初始化信号量
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
// 创建生产者线程
for (i = 0; i < PRODUCER_NUM; i++) {
producer_args[i] = i + 1;
pthread_create(&producers[i], NULL, producer, &producer_args[i]);
}
// 创建消费者线程
for (i = 0; i < CONSUMER_NUM; i++) {
consumer_args[i] = i + 1;
pthread_create(&consumers[i], NULL, consumer, &consumer_args[i]);
}
// 等待生产者线程结束
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producers[i], NULL);
}
// 等待消费者线程结束
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumers[i], NULL);
}
// 销毁信号量
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
```
阅读全文