Mutexes and locking

yazd yazan.dabain at gmail.com
Mon Mar 3 10:03:14 PST 2014


On Monday, 3 March 2014 at 08:18:04 UTC, alexhairyman wrote:
> On Monday, 3 March 2014 at 07:38:05 UTC, Ali Çehreli wrote:
>> 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.
>
> Oh okay, that makes sense.
>
>>
>> > 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
>
> Okay, so when doing something like this
>
> Mutex hashlock;
> void tdigest(string path)
> {
>   MD5Digest thasher = new MD5Digest;
>   thasher.put(read(path)); //read the path in to the MD5 API
>   hashlock.lock();
>   hashkey[path] = thasher.finish();
>   hashlock.unlock();
> }
> void main()
> {
>   hashlock = new Mutex();
> ... other stuff
>   foreach(string s ; tp.parallel(array of strings))
>   {
>     tdigest(s);
>   }
> ... even more stuff
> }
>
> it will fail because the parallel foreach uses the main thread 
> is being used which does some funky stuff? I'm trying to figure 
> out how to implement this (for reference I'm just trying to 
> create a big hash map of files and their md5's)

You have to remember that global scope variables are thread-local 
by default. So your hashlock mutex is actually only initialized 
in the main thread. Try adding __gshared before declaring 
hashlock and see if it works.


More information about the Digitalmars-d-learn mailing list