我尝试用c ++ 11编写一个生产者 - 消费者演示,但是发生了一个棘手的问题。这就是代码
#include <iostream>
#include <thread>
#include <condition_variable>
#include <windows.h>
using namespace std;
std::condition_variable pcv,ccv;
std::mutex m,m1;
const int N=10;
int buf[N];
int count=0;
void producer(){
Sleep(100);
while(true){
std::unique_lock<std::mutex> pulk(m);
while(count==N)
pcv.wait(pulk);
buf[count++]=1;
cout<<"produce data on the buff: "<<count<<endl;
while(count==1) //if I remove this no problem
ccv.notify_one();
pulk.unlock();
}
}
void consumer(){
while(true){
std::unique_lock<std::mutex> culk(m);
while(count==0)
ccv.wait(culk);
buf[--count]=0;
cout<<"consume data on the buff: "<<count<<endl;
while(count==N-1) //if I remove no problem
pcv.notify_one();
culk.unlock();
}
}
int main(int argc,char **argv){
std::thread pro(producer);
std::thread con(consumer);
pro.join();
con.join();
return 0;
程序将永远运行下一行
while(count==1) //if the buffer empty?
ccv.notify_one()