synchronized (this[.classinfo]) in druntime and phobos

Steven Schveighoffer schveiguy at yahoo.com
Wed May 30 12:03:20 PDT 2012


On Wed, 30 May 2012 14:32:59 -0400, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> On 5/30/12 10:47 AM, Steven Schveighoffer wrote:
>> Yes, you can just use a private mutex. But doesn't that just lead to
>> recommending not using a feature of the language?
>
> I don't think so. Synchronized classes are the unit of scoped locking in  
> D. If you want to do all scoped locking internally, make the class  
> private.

Maybe you didn't read thoroughly the first part of my post (the example  
that shows a deadlock that is easily preventable if the mutex isn't  
exposed).  The issue is that it's possible to hijack the mutex that you  
are using to protect the class data in order to protect *external* data.   
Hijacking is not possible if the mutex is private (i.e. a private member).

So great!  Just don't use the builtin object mutex, because it exposes  
possible race conditions.  But then why do we have it (the object hidden  
mutex)?  And now I can't use synchronized classes to ensure the whole  
thing is protected, I have to write all my functions like this:

void foo()
{
    synchronized(this.mutex) // lock a private mutex
    {
    }
}

-Steve


More information about the Digitalmars-d mailing list