James Dennett jdennett at acm.org
Sat Jul 28 22:01:27 PDT 2007

Jason House wrote:
> Sean Kelly wrote:
>> Jason House wrote:
>>> tryLock does not seem to work as I expected.  I thought it returns if
>>> it was successful or not.  What could possibly cause the code below
>>> to fail?  I'm using linux.
>>> myMutex.tryLock();
>>> assert(myMutex.tryLock() == false); // fails
>> Locks in Tango are recursive, so you're guaranteed to succeed if you
>> already hold the lock.
>> Sean
> Does that mean that the mutex locking and unlocking calls are thread
> aware?  A given thread can repeatedly lock a mutex but must then unlock
> it the same number of times before the mutex is released for another
> thread to access it?
> I was trying to be creative with some queue structures.  I wanted to add
> a blocking version of pop.  If nothing is in the queue, wait for that to
> change...  I was thinking that if I had a mutex that was automatically
> locked when the queue was empty, then I could implement blocking by
> quickly grabbing, then releasing a mutex.  For an empty queue, the lock
> would sit and wait.
> It sounds like I can't use tango's Mutex class for this purpose because
> the push's and pop's are done by different threads.  In fact, push calls
> are done by lots of threads.  Is there anything in tango.core.sync that
> I should be using for this purpose?

Aside from D, many system APIs for mutexes require that locking
and unlocking be done by the same thread.  Some will allow it to
work across threads, and on some it will tend to work across
threads until you turn on debugging options which will alert
you to the potential problem.

If D aims to be somewhat portable, it likely won't want to
support designs which lock a mutex in one thread and then
unlock it from another.

-- James

More information about the Digitalmars-d-learn mailing list