Using condition variable in a producer-consumer situation

后端 未结 1 1540
感动是毒
感动是毒 2020-12-03 01:12

I\'m trying to learn about condition variables and how to use it in a producer-consumer situation. I have a queue where one thread pushes numbers into the queue while anothe

相关标签:
1条回答
  • 2020-12-03 01:46

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题