直接上代码
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <queue>
std::mutex mut;
std::queue<int> queData;
std::condition_variable cond;
#define MAX_NUM 20
int nCnt=0;
void Product()
{
while (true) {
std::unique_lock<std::mutex>lk(mut);
cond.wait(lk,[]{
if(queData.size() > MAX_NUM)
{
return false;
}else
{
return true;
}
});
queData.push(nCnt);
std::cout << "this id " << std::this_thread::get_id() <<", Insert a num,cur que size " << queData.size() << std::endl;
nCnt++;
cond.notify_one();
lk.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void Customer()
{
while (true) {
std::cout << "wait " << std::endl;
std::unique_lock<std::mutex>lk(mut);
cond.wait(lk,[]{
return queData.size() >0;
});
int cmd = queData.front();
queData.pop();
std::cout << "this id " << std::this_thread::get_id() <<", pop a num is " << cmd << ",cur que size is " << queData.size() << std::endl;
cond.notify_one();
}
}
int main()
{
std::thread th = std::thread(Customer);
std::thread th2 = std::thread(Product);
th.join();
th2.join();
return 0; //由于上面两个线程中存在while循环,没有退出条件,所以该行代码不会执行。可以按照实际条件(如回调函数)对上面两个线程中while条件修改。
}
Qt的.pro文件信息如下:
TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += \
main.cpp
LIBS += -lpthread
直接结果如下:
关于线程中使用的互斥量和条件变量可参考链接: