用c++写生产者—消费者问题
时间: 2023-08-12 19:06:56 浏览: 42
生产者-消费者问题是经典的并发问题,可以使用多种编程语言来实现解决方案。以下是使用 C++ 实现生产者-消费者问题的示例代码:
```c++
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
const int MAX_QUEUE_SIZE = 10;
queue<int> q;
mutex mtx;
condition_variable cv;
// 生产者线程函数
void producer() {
for (int i = 0; i < 100; i++) {
unique_lock<mutex> lock(mtx);
cv.wait(lock, []() { return q.size() < MAX_QUEUE_SIZE; }); // 等待队列不满
q.push(i);
cout << "Produced: " << i << endl;
cv.notify_one();
}
}
// 消费者线程函数
void consumer() {
while (true) {
unique_lock<mutex> lock(mtx);
cv.wait(lock, []() { return !q.empty(); }); // 等待队列不空
int x = q.front();
q.pop();
cout << "Consumed: " << x << endl;
cv.notify_one();
}
}
int main() {
thread t1(producer);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}
```
在这个示例中,我们使用了 STL 中的队列来模拟生产者-消费者问题中的共享数据。我们使用互斥锁 `mtx` 来保证线程安全,并使用条件变量 `cv` 来实现线程间同步。在生产者线程中,我们使用 `wait` 函数等待队列不满,然后将数据压入队列,并通知消费者线程。在消费者线程中,我们使用 `wait` 函数等待队列不空,然后从队列中取出数据,并通知生产者线程。通过互斥锁和条件变量的配合使用,我们可以实现生产者和消费者之间的正确同步。