#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <condition_variable>//条件变量
#include <queue>//任务队列
std::queue<int> g_queue;
std::condition_variable g_cv;
std::mutex mtx;
void Producer() {
for (int i = 0; i < 10; i++) {
std::unique_lock<std::mutex> lock(mtx);//放任务的时候,上锁,不允许消费者取任务
g_queue.push(i);//放任务
g_cv.notify_one();//通知消费者消费
std::cout << "Producer:" << i << std::endl;
}
std::this_thread::sleep_for((std::chrono::microseconds(100)));
}
void Consumer() {
while (1) {
std::unique_lock<std::mutex> lock(mtx);//取任务的时候上锁,不影响生产者放任务
g_cv.wait( lock, []() {
return !g_queue.empty();
});//队列为空,阻塞
int value = g_queue.front();//取任务
g_queue.pop();
std::cout << "Consumer:" << value << std::endl;
}
}
int main() {
std::thread t1(Producer);
std::thread t2(Consumer);
t1.join();
t2.join();
return 0;
}
如果任务队列为空,就会阻塞消费者进程,如下代码所示:
g_cv.wait( lock, []() { return !g_queue.empty(); });
当生产者生成了商品后,就会通知消费者进程解除阻塞,如下代码所示:
g_cv.notify_one();//通知消费者消费