#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <condition_variable>
#include <queue>
#include <Windows.h>
using namespace std;
queue<int> g_queue;
condition_variable g_cv;
mutex mtx;
void Producer(){
for (size_t i = 0; i < 10; i++){
{
unique_lock<mutex> lock(mtx);
g_queue.push(i);
//通知消费者来取任务
g_cv.notify_one();
cout << "put:" << i << endl;
}
Sleep(100);
}
return;
}
void Consumer() {
while (true)
{
unique_lock<mutex> lock(mtx);
//等待
g_cv.wait(lock, []() {
return !g_queue.empty();
});
int value = g_queue.front();
cout << "take:" << value << endl;
g_queue.pop();
}
}
int main(){
thread thread1(Producer);
thread thread2(Consumer);
thread1.join();
thread2.join();
system("pause");
return 0;
}
C++11多线程编程-生产者消费者模型
最新推荐文章于 2024-07-15 15:17:48 发布