编写C程序,用信号量机制实现生产者-消费者问题。
时间: 2024-05-09 17:14:35 浏览: 7
好的!以下是一个简单的生产者-消费者问题的C程序,使用信号量机制实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 10 // 缓冲区大小
int buffer[BUFFER_SIZE]; // 缓冲区
int in = 0, out = 0; // 生产者和消费者的指针
sem_t empty, full, mutex; // 信号量:空闲缓冲区、已满缓冲区、互斥锁
void *producer(void *arg) {
int item;
while (1) {
item = rand() % 100; // 随机产生一个生产者要生产的物品
sem_wait(&empty); // 等待空闲缓冲区
sem_wait(&mutex); // 加锁
buffer[in] = item; // 将物品放入缓冲区
printf("Producer produced item %d at position %d\n", item, in);
in = (in + 1) % BUFFER_SIZE; // 更新指针
sem_post(&mutex); // 解锁
sem_post(&full); // 发送已满信号
sleep(1); // 生产者休息一秒钟
}
}
void *consumer(void *arg) {
int item;
while (1) {
sem_wait(&full); // 等待已满缓冲区
sem_wait(&mutex); // 加锁
item = buffer[out]; // 从缓冲区取出物品
printf("Consumer consumed item %d at position %d\n", item, out);
out = (out + 1) % BUFFER_SIZE; // 更新指针
sem_post(&mutex); // 解锁
sem_post(&empty); // 发送空闲信号
sleep(2); // 消费者休息两秒钟
}
}
int main() {
pthread_t tid1, tid2;
sem_init(&empty, 0, BUFFER_SIZE); // 初始化信号量
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
pthread_create(&tid1, NULL, producer, NULL); // 创建生产者线程
pthread_create(&tid2, NULL, consumer, NULL); // 创建消费者线程
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&empty); // 销毁信号量
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
```
在这个程序中,我们使用了三个信号量:`empty`、`full` 和 `mutex`。其中,`empty` 信号量表示空闲缓冲区的数量,`full` 信号量表示已满缓冲区的数量,`mutex` 信号量用于实现互斥锁。
生产者和消费者的线程函数分别为 `producer` 和 `consumer`,它们会不断地生产和消费物品。在生产者线程中,我们先随机生成一个生产者要生产的物品,然后等待空闲缓冲区的信号量,加锁,将物品放入缓冲区,更新指针,解锁,发送已满信号,最后休息一秒钟。在消费者线程中,我们等待已满缓冲区的信号量,加锁,从缓冲区取出物品,更新指针,解锁,发送空闲信号,最后休息两秒钟。
最后,在 `main` 函数中,我们初始化了三个信号量,创建了生产者和消费者的线程,等待线程结束,然后销毁信号量。