写一个c++版本的生产者消费者样例
时间: 2024-05-13 08:14:00 浏览: 9
下面是一个简单的C语言版的生产者消费者样例:
```
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_t mutex, empty, full;
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);
}
}
int main() {
pthread_t prod_tid, cons_tid;
sem_init(&mutex, 0, 1); // 初始化互斥锁
sem_init(&empty, 0, BUFFER_SIZE); // 初始化缓冲区空槽数量
sem_init(&full, 0, 0); // 初始化缓冲区满槽数量
pthread_create(&prod_tid, NULL, producer, NULL); // 创建生产者线程
pthread_create(&cons_tid, NULL, consumer, NULL); // 创建消费者线程
pthread_join(prod_tid, NULL);
pthread_join(cons_tid, NULL);
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}
```
在这个样例中,我们使用了三个信号量来实现生产者消费者模型:
- mutex:互斥锁,用于保护缓冲区的访问。
- empty:缓冲区空槽数量,表示缓冲区中还剩余多少空位,当空槽数量为0时,生产者线程将被阻塞。
- full:缓冲区满槽数量,表示缓冲区中已经存储了多少个物品,当满槽数量为0时,消费者线程将被阻塞。