编写程序,使用Linux操作系统中的信号量机制模拟实现生产者-消费者问题。设有一个生产者和一个消费者,缓冲区可以存放产品,生产者不断生成产品放入缓冲区,消费者不断从缓冲区中取出产品,消费产品。
时间: 2024-05-12 14:13:48 浏览: 10
下面是一个使用信号量机制模拟实现生产者-消费者问题的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5 // 缓冲区大小
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0; // 生产者放置产品的位置
int out = 0; // 消费者取产品的位置
sem_t mutex, empty, full; // 三个信号量
void *producer(void *arg); // 生产者函数
void *consumer(void *arg); // 消费者函数
int main()
{
pthread_t producer_thread, consumer_thread; // 生产者和消费者线程
// 初始化信号量
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
// 创建生产者和消费者线程
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(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
void *producer(void *arg)
{
int item;
while (1) {
// 生产产品
item = rand() % 100;
// 等待缓冲区不满
sem_wait(&empty);
// 互斥访问缓冲区
sem_wait(&mutex);
// 将产品放入缓冲区
buffer[in] = item;
printf("Producer produces item %d at %d\n", item, in);
in = (in + 1) % BUFFER_SIZE;
// 释放互斥锁
sem_post(&mutex);
// 发送信号通知缓冲区有产品可取
sem_post(&full);
// 等待一段时间
sleep(rand() % 3);
}
pthread_exit(NULL);
}
void *consumer(void *arg)
{
int item;
while (1) {
// 等待缓冲区有产品可取
sem_wait(&full);
// 互斥访问缓冲区
sem_wait(&mutex);
// 从缓冲区取出产品
item = buffer[out];
printf("Consumer consumes item %d at %d\n", item, out);
out = (out + 1) % BUFFER_SIZE;
// 释放互斥锁
sem_post(&mutex);
// 发送信号通知缓冲区有空位可放
sem_post(&empty);
// 等待一段时间
sleep(rand() % 3);
}
pthread_exit(NULL);
}
```
在这个程序中,我们使用了三个信号量 mutex、empty 和 full 来实现生产者-消费者问题。其中,mutex 用于互斥访问缓冲区,empty 用于表示缓冲区是否为空,full 用于表示缓冲区是否已满。
在生产者函数中,我们先生成一个产品,然后等待缓冲区不满,再使用互斥锁访问缓冲区,将产品放入缓冲区,释放互斥锁,发送信号通知缓冲区有产品可取,并等待一段时间。
在消费者函数中,我们先等待缓冲区有产品可取,再使用互斥锁访问缓冲区,从缓冲区取出产品,释放互斥锁,发送信号通知缓冲区有空位可放,并等待一段时间。
需要注意的是,在主函数中我们要先初始化信号量,然后创建生产者和消费者线程,等待它们结束后再销毁信号量。另外,我们使用了 rand() 函数来生成随机数,这样可以模拟生产者和消费者的不确定性。