在main函数下创建两个线程,一个线程为生产者线程,一个线程为消费者线程
时间: 2023-11-28 07:57:06 浏览: 105
好的,你可以参考下面的代码示例:
```c++
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> q;
void producer() {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
q.push(i);
std::cout << "Produced: " << i << std::endl;
lock.unlock();
cv.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // 休眠500ms
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return !q.empty(); });
int x = q.front();
q.pop();
std::cout << "Consumed: " << x << std::endl;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // 休眠1000ms
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
```
在上面的代码中,我们使用了一个互斥锁 `mtx` 和一个条件变量 `cv` 来实现线程之间的同步和通信。生产者线程 `producer` 不断地向队列 `q` 中添加元素,每添加一个元素就通知消费者线程 `consumer`,然后休眠 500 毫秒。消费者线程则在每次从队列 `q` 中取出一个元素后,会打印出来,并且休眠 1000 毫秒。在 `main` 函数中,我们创建了两个线程 `t1` 和 `t2` 分别执行生产者线程和消费者线程,并等待它们完成执行再退出程序。