2016-04-10 5 views
-1

abgestürzt versuche ich mit C++ 11 eine Erzeuger-Verbraucher-Demo zu schreiben, aber ein heikles Problem happend.Here ist der Codewarum diese Producer-Consumer-Demo?

#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; 

das Programm der nächste Zeile läuft für immer

while(count==1) //if the buffer empty? 
    ccv.notify_one() 

ich versuche GDB zu verwenden aus diesem Grund finden, aber kein Ergebnis Hier ist der GDB Ausgang enter image description here

Antwort

1

Die Linien while(count==1) //if I remove this no problem und while(count==N-1) //if I remove no problem machen Ihre Synchronisation fragil. Sie betrachten nur zwei Zustände von zehn (N) möglich.