Using condition variable in a producer-consumer situation Using condition variable in a producer-consumer situation multithreading multithreading

Using condition variable in a producer-consumer situation


You have to use the same mutex to guard the queue as you use in the condition variable.

This should be all you need:

void consume(){    while( !bStop )    {        boost::scoped_lock lock( mutexQ);        // Process data        while( messageQ.empty() ) // while - to guard agains spurious wakeups        {            condQ.wait( lock );        }        string s = messageQ.front();                    messageQ.pop();    }}void produce(){    int i = 0;    while(( !bStop ) && ( i < MESSAGE ))    {        stringstream out;        out << i;        string s = out.str();        boost::mutex::scoped_lock lock( mutexQ );        messageQ.push( s );        i++;        condQ.notify_one();    }}