Mutexes and locking

Ali Çehreli acehreli at yahoo.com
Sun Mar 2 23:38:05 PST 2014


On 03/02/2014 10:38 PM, alexhairyman wrote:

 > I think I'm missing something big, but I'm having troubles with mutexes
 > (using in a parallel foreach loop somewhere else); Why do the trylocks
 > return true shouldn't they return false because the mutex is already
 > locked?

The documentation says that Mutex is a recursive lock, meaning that the 
holder of the lock can lock it even further. :) There is an internal 
reference count so that the lock must be unlocked the equal number of 
times that it has been locked.

 > I don't think this is a phobos bug, I'm on OSX using dmd 2.065
 >
 > import core.sync.mutex;
 > import std.stdio;
 >
 > void main()
 > {
 >    Mutex m = new Mutex;
 >    m.lock();
 >    writefln("%s", m.tryLock());
 >    writefln("%s", m.tryLock());

The lock count is now 3. You must unlock it 3 times so that another 
thread can lock it.

 >    return;
 > }
 >
 > produces:
 > true
 > true
 >
 > Thanks!
 >    Alex

Ali



More information about the Digitalmars-d-learn mailing list