生产者消费者代码C++
时间: 2024-04-17 13:19:30 浏览: 75
生产者消费者问题 C++ 代码实现
以下是一个简单的C++生产者消费者代码示例:
```cpp
#include <iostream>
#include <deque>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;
deque<int> q;
mutex mu;
condition_variable cond;
void producer() {
int count = 10;
while (count > 0) {
unique_lock<mutex> locker(mu);
q.push_front(count);
locker.unlock();
cond.notify_one();
count--;
}
}
void consumer() {
int data = 0;
while (data != 1) {
unique_lock<mutex> locker(mu);
cond.wait(locker, [](){return !q.empty();});
data = q.back();
q.pop_back();
locker.unlock();
cout << "Consumer got a value from producer: " << data << endl;
}
}
int main() {
thread t1(producer);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}
```
该示例中,生产者线程不断向队列中添加数据,消费者线程则从队列中取出数据并进行处理。其中,互斥锁和条件变量用于保证线程安全和线程之间的同步。在条件变量的wait函数中,lambda表达式用于判断队列是否为空,如果为空则挂起消费者线程,直到有新的数据被添加到队列中。
阅读全文