tango.core.sync.Mutex.tryLock

Sean Kelly sean at f4.ca
Mon Jul 30 10:03:11 PDT 2007


Jason House wrote:
> Sean Kelly wrote:
>> You should look at Condition.  Use is something like this:
>>
>> auto myMutex = new Mutex;
>> auto myCondition = new Condition( myMutex );
>>
>> Thread A (producer):
>>
>> synchronized( myMutex ) {
>>     myQueue.push( data );
>>     myCond.notify();
>> }
>>
>> Thread B (consumer):
>>
>> synchronized( myMutex ) {
>>     while( myQueue.isEmpty )
>>         myCond.wait();
>> }
> 
> 
> Correct me if I'm wrong, but the Mutex operation of tango does not do 
> strange interaction with the synchronized keyword?  Wouldn't Thread B's 
> "synchrnoized( myMutex )" cause Thread A to be unable to enter its 
> "synchronized( myMutex )"?

Normally, yes.  But myCond.wait() unlocks the mutex, allowing Thread A 
to enter.  When wait returns, the lock is re-acquired.

>> In essence, Conditions are associated with a specific mutex, which is 
>> atomically unlocked when wait() is called.  Thus, when thread B waits 
>> it allows thread A to enter the protected region to add more data to 
>> the queue.  When wait unblocks it atomically acquires the mutex again, 
>> by which time thread A will have exited the protected region (earlier 
>> implementations actually blocked thread A and simply transferred 
>> control--this was indicated by 'signal' rather than 'notify').


Sean


More information about the Digitalmars-d-learn mailing list