用c++写一个生产者和消费者
时间: 2024-05-04 09:18:45 浏览: 14
下面是一个简单的生产者和消费者的C++程序:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
mutex mtx;
condition_variable cv;
queue<int> q;
void producer()
{
for (int i = 1; i <= 10; i++)
{
unique_lock<mutex> lck(mtx);
q.push(i);
cout << "Producer pushed: " << i << endl;
cv.notify_all();
lck.unlock();
this_thread::sleep_for(chrono::milliseconds(500));
}
}
void consumer()
{
while (true)
{
unique_lock<mutex> lck(mtx);
cv.wait(lck, [] { return !q.empty(); });
int val = q.front();
q.pop();
cout << "Consumer popped: " << val << endl;
lck.unlock();
this_thread::sleep_for(chrono::milliseconds(1000));
}
}
int main()
{
thread t1(producer);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}
```
在这个程序中,我们使用了一个互斥锁和条件变量来实现线程之间的同步。生产者线程不断地向队列中插入数字,消费者线程则等待队列非空,然后弹出队头的数字进行消费。注意到我们在生产者线程中使用了`notify_all()`函数来通知消费者线程队列中有新的数字可以消费。
需要注意的是,这个程序中没有考虑线程安全的问题,比如多个生产者同时插入数字或多个消费者同时弹出数字,这时需要使用更高级的同步机制来解决。