C++多线程学习笔记004简单的Producer和Consumer模型
引言
Producer为队列中添加“任务”,Consumer自队列中取出并完成“任务”。
实列代码
#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
#include<condition_variable>
#include<queue>
std::queue<int> queue1;
std::condition_variable condtval1;
std::mutex mtx;
void Producer() {
for(int i = 0; i < 10; i++){
{
std::unique_lock<std::mutex> unlck(mtx);
queue1.push(i);
condtval1.notify_one();
std::cout << "Producer : " << i << std::endl;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
void Consumer() {
while(1){
std::unique_lock<std::mutex> unlck(mtx);
condtval1.wait(unlck, [] () {return !queue1.empty();});
int val = queue1.front();
queue1.pop();
std::cout << "Consumer : " << val << std::endl;
}
}
int num {0};
int main(){
std::thread thread1(Producer);
std::thread thread2(Consumer);
thread1.join();
thread2.join();
std::cout <<"over" << std::endl;
return 0;
}
// g++ ./XXX.cpp -o ./XXX -pthread