Mutexes and locking

Ali Çehreli acehreli at yahoo.com
Wed Mar 5 10:50:59 PST 2014


On 03/05/2014 09:49 AM, Jeremy DeHaan wrote:

 > On Monday, 3 March 2014 at 07:38:05 UTC, Ali Çehreli wrote:
 >> 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.
 >
 >
 >
 > Maybe this is because I haven't done much work with multi-threading,

Same here. :) I have learned about this concept years ago at a company 
that I had joined recently. I wrote a function like the following:

void foo()
{
     lock(mutex);

     // ... code that needs to be protected by a lock ...

     unlock(mutex);
}

The problem was, foo() could be called from different contexts, some of 
which had already locked the same mutex. I was told that I could not do 
that because the lock was not recursive.

 > It makes sense to me that a mutex should be
 > allowed to be locked only once, and anything else trying to lock it
 > get's held up until it has been unlocked,

This design does not differentiate the same thread as somebody else and 
allows what I had tried to do above.

Of course, I could have checked whether the lock was owned by me and 
then lock otherwise, but doing that becomes unnecessary here.

 > and this may seem like a silly question(like I said, not much
 > multi-threading experience), but what determines the holder of a lock?
 > Is it the thread or is it a specific function? Or something else?

I think it is the thread.

Ali



More information about the Digitalmars-d-learn mailing list