Boost logo

Threads-Devel :

Subject: Re: [Threads-devel] wait/notify_one problem
From: Anthony Williams (anthony_at_[hidden])
Date: 2009-06-17 03:14:43


Siegal, Sara wrote:
> Hi,
>
> I'm trying to use condition variables in a pretty classic producer/consumer problem. I've done some research that makes me think condition variables are the way to go, but I can't seem to get the implementation right. The producer and consumer are both member functions of a class which has the mutex (readyListMutex) as a class member.
>
> The Producer:
> void WFOVProcessor::frameCallback(int32_t frame) {
> cout << "WFOVProcessor::frameCallback" << endl;
> CaptureRequest req;
> // ...fill in the CaptureRequest data structure here...
> cout << "WFOVProcessor::frameCallback scoped_lock" << endl;
> boost::mutex::scoped_lock lock(m_readyListMutex);
> cout << "WFOVProcessor::frameCallback push_back" << endl;
> m_readyList.push_back( req );
> cout << "WFOVProcessor::frameCallback notify_one" << endl;
> lock.unlock( );
> m_readyListCondition.notify_one( );
> }
>
> The Consumer:
> while ( true ) {
> cout << "WFOVProcessor::background before readyLock" << endl;
> boost::mutex::scoped_lock readyLock(m_readyListMutex);
> cout << "WFOVProcessor::background after readyLock" << endl;
> if ( ! m_running ) break;
> if ( m_readyList.size( ) == 0 ) {
> do {
> cout << "before WFOVProcessor::background loop m_readyListCondition.wait" << endl;
> m_readyListCondition.wait(readyLock);
> cout << "after WFOVProcessor::background loop m_readyListCondition.wait" << endl;
> } while( !m_readyList.size( ) && m_running );
> if ( ! m_running ) break;
> }
> CaptureRequest req = m_readyList[0];
> m_readyList.pop_front( );
> // ...do something with the request...
> }
>
> The output when I run my program (32 bit linux):
> WFOVProcessor::background before readyLock
> WFOVProcessor::background after readyLock
> before WFOVProcessor::background loop m_readyListCondition.wait WFOVProcessor::frameCallback
> WFOVProcessor::frameCallback scoped_lock
>
> When the producer tries to obtain the lock, it waits forever. What am I doing wrong? Is the order incorrect?

At first glance, this appears OK. How are you starting the threads and
managing their lifetime and the lifetime of "this"?

> For debugging purposes, is it possible to query the state of a mutex?

No.

You might find it useful to look at my example producer/consumer queue
at
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

Anthony

-- 
Author of C++ Concurrency in Action | http://www.manning.com/williams
just::thread C++0x thread library   | http://www.stdthread.co.uk
Just Software Solutions Ltd         | http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

Threads-Devel list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk