头文件 和 全局变量
消费者

生产者

main函数

代码
#include <iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<queue>
using namespace std;
queue<int>products ;
mutex m ;
condition_variable cond ;
bool notify = false ;
bool done = false ;
void consumer(){
while(!done){
unique_lock<mutex>lk(m);
while(!notify){
cond.wait(lk);
}
while(!products.empty()){
cout<<"consumer:"<<products.front()<<endl;
products.pop();
notify = false ;
cond.notify_one();
}
}
}
void producer(){
int i ;
for(i=0;i<10;i++){
unique_lock<mutex>lk(m);
cout<<"producer..."<<i<<endl;
while(notify||!products.empty()){
cond.wait(lk);
}
products.push(i);
notify = true ;
cond.notify_one();
}
done = true ;
cond.notify_one();
}
int main()
{
thread t1(producer);
thread t2(consumer);
t1.join();
t2.join();
return 0;
}