c语言数据结构实现操作系统生产者消费者问题实现循环利用缓冲区
时间: 2024-05-24 11:12:47 浏览: 158
以下是用C语言实现生产者消费者问题的循环利用缓冲区的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5 //缓冲区大小
#define PRODUCER_NUM 3 //生产者数量
#define CONSUMER_NUM 2 //消费者数量
int buffer[BUFFER_SIZE]; //缓冲区数组
int in = 0; //生产者向缓冲区中添加数据的索引
int out = 0; //消费者从缓冲区中取出数据的索引
sem_t empty; //空闲位置信号量
sem_t full; //已用位置信号量
pthread_mutex_t mutex; //互斥锁
void *producer(void *args) //生产者线程函数
{
int id = *(int *)args;
while (1) {
int item = rand() % 100; //生成随机数
sem_wait(&empty); //等待空闲位置
pthread_mutex_lock(&mutex); //加锁
buffer[in] = item; //将数据添加到缓冲区
printf("Producer %d produced %d.\n", id, item);
in = (in + 1) % BUFFER_SIZE; //更新索引
pthread_mutex_unlock(&mutex); //解锁
sem_post(&full); //增加已用位置
sleep(rand() % 3); //随机休眠
}
}
void *consumer(void *args) //消费者线程函数
{
int id = *(int *)args;
while (1) {
sem_wait(&full); //等待已用位置
pthread_mutex_lock(&mutex); //加锁
int item = buffer[out]; //从缓冲区中取出数据
printf("Consumer %d consumed %d.\n", id, item);
out = (out + 1) % BUFFER_SIZE; //更新索引
pthread_mutex_unlock(&mutex); //解锁
sem_post(&empty); //增加空闲位置
sleep(rand() % 3); //随机休眠
}
}
int main()
{
srand(time(NULL));
sem_init(&empty, 0, BUFFER_SIZE); //初始化空闲位置信号量
sem_init(&full, 0, 0); //初始化已用位置信号量
pthread_mutex_init(&mutex, NULL); //初始化互斥锁
pthread_t producer_threads[PRODUCER_NUM]; //生产者线程数组
pthread_t consumer_threads[CONSUMER_NUM]; //消费者线程数组
int producer_ids[PRODUCER_NUM]; //生产者线程ID数组
int consumer_ids[CONSUMER_NUM]; //消费者线程ID数组
int i;
for (i = 0; i < PRODUCER_NUM; i++) {
producer_ids[i] = i + 1;
pthread_create(&producer_threads[i], NULL, producer, &producer_ids[i]); //创建生产者线程
}
for (i = 0; i < CONSUMER_NUM; i++) {
consumer_ids[i] = i + 1;
pthread_create(&consumer_threads[i], NULL, consumer, &consumer_ids[i]); //创建消费者线程
}
for (i = 0; i < PRODUCER_NUM; i++) {
pthread_join(producer_threads[i], NULL); //等待生产者线程结束
}
for (i = 0; i < CONSUMER_NUM; i++) {
pthread_join(consumer_threads[i], NULL); //等待消费者线程结束
}
sem_destroy(&empty); //销毁空闲位置信号量
sem_destroy(&full); //销毁已用位置信号量
pthread_mutex_destroy(&mutex); //销毁互斥锁
return 0;
}
阅读全文