生产者消费者问题c++
时间: 2023-10-18 17:09:48 浏览: 46
生产者消费者问题是一个经典的同步问题,其主要涉及到两个线程间的协调和互斥,其中一个线程为生产者,负责生产产品;另一个线程为消费者,负责消费产品。生产者和消费者在共享的缓冲区中交换产品。
下面是一个使用 C++ 编写的生产者消费者问题的例子:
```C++
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <queue>
using namespace std;
queue<int> q;
sem_t empty, full, mutex;
void *producer(void *arg) {
for (int i = 0; i < 10; i++) {
sem_wait(&empty);
sem_wait(&mutex);
q.push(i);
cout << "Produced: " << i << endl;
sem_post(&mutex);
sem_post(&full);
}
pthread_exit(NULL);
}
void *consumer(void *arg) {
for (int i = 0; i < 10; i++) {
sem_wait(&full);
sem_wait(&mutex);
int data = q.front();
q.pop();
cout << "Consumed: " << data << endl;
sem_post(&mutex);
sem_post(&empty);
}
pthread_exit(NULL);
}
int main() {
pthread_t tid[2];
sem_init(&empty, 0, 10);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
pthread_create(&tid[0], NULL, producer, NULL);
pthread_create(&tid[1], NULL, consumer, NULL);
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
```
在上面的例子中,我们使用了 POSIX 线程库中的 `pthread` 和 `semaphore`,并创建了两个线程,生产者和消费者。缓冲区使用了 STL 中的 `queue`。我们定义了三个信号量:`empty`,`full` 和 `mutex`,分别表示空闲缓冲区的数量,已占用缓冲区的数量和互斥锁。在生产者和消费者线程中,我们使用了 `sem_wait` 和 `sem_post` 方法来进行同步和互斥操作。在主函数中,我们创建了两个线程并等待它们完成,同时在结束程序之前销毁了信号量。
当我们运行这个程序时,我们可以看到生产者会生产 0 到 9 的数字并将它们放入缓冲区中,而消费者会从缓冲区中取出这些数字并将它们消费掉。在同一时刻,缓冲区中最多只能有 10 个数字,因为我们初始化了 `empty` 信号量的值为 10。如果缓冲区已满,生产者线程将会等待,直到有空闲的缓冲区;如果缓冲区为空,消费者线程将会等待,直到有产品可供消费。在任意时刻,只有一个线程能够访问缓冲区,这是由 `mutex` 信号量保证的。