|
Boost Users : |
From: Peter Mackay (mackay.pete+gmane_at_[hidden])
Date: 2006-04-30 07:47:41
Thanks again, that pseudo-code is very much how my code is now, and it seems
to work like a charm.
Peter
"Thomas Costa" <oohrah_at_[hidden]> wrote in message
news:87FBAF99-61EF-47A8-81F5-58C6CAC44126_at_mac.com...
> Very rough psuedo code might look like this code:
>
> while ( true )
> {
> Request myReq;
>
> {
> scopedLock lock( myMutex );
>
> while ( myQueue.empty() )
> myCond.wait( myMutex );
>
> myReq = myQueue.pop();
> }
>
> if ( myReq.isQuitReq() )
> break;
>
> myReq.process();
> }
>
> Note this doesn't handle things like posting results/errors back to
> the queue clients and lots and lots of other things but it's just to
> get a rough idea.
> Notice that the mutex is only locked long enough to check the queue
> and pop elements. The myCond.wait call will release the mutex and
> then reacquire it for you when the cond is signalled.
>
> On Apr 28, 2006, at 2:22 AM, Peter Mackay wrote:
>
>> Hello,
>>
>> Thomas, Thank you very much for your detailed reply.
>>
>>> You usually don't hold the mutex guarding the state indicating
>>> variables for a long time.
>>> You usually hold it just enough to update the variables to indicate
>>> the new state you have transitioned to.
>>
>> Ah, so even though I pass the mutex into the condition when
>> waiting, I don't
>> have to leave the mutex locked while handling the request.
>>
>>> That is you hold it while you pick up the request from the queue and
>>> transfer it to local variables in the thread (or somehow mark it in
>>> the queue) as being processed, then you release the lock and go off
>>> and handle request.
>>
>> That sounds exactly like what I want to do. Thanks.
>>
>>> After you are done processing you grab the lock
>>> again and update state or lock for new requests and then repeat. If
>>> there are no requests then you block on condition while holding the
>>> mutex and the blocking wait releases and reacquires the lock for you
>>> when the condition is signaled. You will be holding the mutex lock
>>> for very little time unless popping/marking queue elements is quite
>>> expensive.
>>
>> I'm planning on just copying the requests to a local variable in
>> the thread
>> function, so this should be okay.
>>
>>> Also, it often a little more efficient to signal the condition
>>> variable while not holding the mutex. It can avoid needless context
>>> ping ponging.
>>
>> Ah, I didn't realise I could do that.
>>
>> Thanks again, you've really helped me out.
>>
>> Peter
>>
>>
>>
>> _______________________________________________
>> Boost-users mailing list
>> Boost-users_at_[hidden]
>> http://lists.boost.org/mailman/listinfo.cgi/boost-users
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net