dimanche 25 janvier 2015

c++ std condition_variable waits for ever even after notify_one and release of lock

I am writing a program to see if I can get input from command line continuously while another thread processes the data and outputs something. I prepared a simple test case where the input from std::cin is added into a queue and then just printed out in fifo manner. However the processing thread which is the printer in this case seems to wait forever for even after the mutex is released from input thread and input thread notifies over the condition_variable.



#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <string>
#include <queue>

using namespace std;

std::mutex mtx;
std::condition_variable cv;

class Network {
public:
std::queue<std::string> buf;
Network() {}
};

struct bufPred {
Network* nw;
bufPred(Network* nw): nw(nw) {}
bool operator()() {return !nw->buf.empty();}
};

void inp(Network* nw) {
while(true) {
std::string s("");
std::cout<<"enter input: ";
std::cin>>s;
std::unique_lock<std::mutex> lck(mtx);
nw->buf.push(s);
cv.notify_one();
}
}

void proc(Network* nw) {
while(true) {
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck, bufPred(nw));
std::cout<<nw->buf.front()<<std::endl;
nw->buf.pop();
}
}

int main() {
Network nw;
std::thread inputs(inp,&nw);
std::thread process(proc,&nw);
inputs.join();
process.join();
return 0;
}


Can someone shed light on this.


Aucun commentaire:

Enregistrer un commentaire