2016-04-10 11 views
-1

私はC++ 11と生産者 - 消費者のデモを書き込もうが、難しい問題happend.Hereは、プログラムは永遠に次の行を実行するコードこの生産者 - 消費者のデモは?

#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() 

私はこの理由を見つけるGDBを使用しようとするが、ここでは何の結果 は、GDB出力されません enter image description here

答えて

1

ラインwhile(count==1) //if I remove this no problemwhile(count==N-1) //if I remove no problemは、同期を壊れやすくします。あなたは10の2つの状態(N)しか考えられません。

関連する問題