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

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Wed May 30 09:08:57 PDT 2012


On 5/30/12 6:10 AM, Regan Heath wrote:
> Ultimately the "problem" that needs solving is the fact that
> synchronized classes/methods use a public mutex and this exposure makes
> deadlocks more likely. I was hoping that by giving some examples in
> code, it would become clearer to the people who don't see what all the
> fuss is about.

How do free-floating mutexes that are not explicitly associated with 
_any_ data make deadlocks less likely? In my experience the less 
structured mutexes are worse, not better.

> Yes, having to manually create a mutex is a pain, and as Andrei has
> mentioned a few times having 2 separate things (one object to lock, one
> mutex) which conceptually should be one thing is worse from an
> understanding/maintenance point of view, however..
>
> 1. If the mutex is intended to lock a single object then we can make the
> following options available:
> a. A Lockable class to derive from.
> b. A Lockable struct to compose with (assuming here that the struct will
> be created/destroyed with the object).
> c. A Lockable!(T) wrapper template/struct/class to wrap objects to be
> locked.
> d. A Lockable interface which classes may implement.
> e. Some sort of compiler magic where it supplies the mutex for
> objects/methods marked with "synchronized" or involved in a
> synchronized(object) statement.
>
> 2. If the scope of the locking is greater than a single object, then a
> separate mutex is required/desired anyway.

But all of these are available in the current design. You have 
synchronized classes for the likes of 1a and the core mutex for creating 
all others except e.

> 1a. would contain a mutex primitive and lock/tryLock/unlock methods (it
> would implement the interface in 1d)
>
> 1b. would also contain a mutex primitive and alias could be used to
> expose the lock/tryLock/unlock methods (it would implement the interface
> in 1d)
>
> 1c. is actually a technique I have used a lot in C++ where the template
> class is created on the stack of a function/critical section and it
> (optionally) locks on creation (or later when lock() is called) and
> always unlocks on destruction as it leaves scope (by any means). It's a
> very robust pattern, and is similar (the inspiration/or result) of/to
> the synchronized block itself.

Yah, we use it a lot at Facebook. We probably should have such a wrapper 
in the standard library.

> IMO, the wasted space used by the monitor isn't ideal, but it's not a
> "problem" for the general case. It is a problem for people with limited
> memory environments but that's another topic. Talking about both is only
> clouding the discussional waters so to speak.

I agree.


Andrei



More information about the Digitalmars-d mailing list