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

Alex Rønne Petersen alex at lycus.org
Tue May 29 16:06:06 PDT 2012


On 30-05-2012 00:35, Jonathan M Davis wrote:
> On Wednesday, May 30, 2012 00:01:49 Alex Rønne Petersen wrote:
>> Besides, it seems to me that D can't quite make up its mind. We have TLS
>> by default, and we encourage message-passing (through a library
>> mechanism), and then we have the synchronized statement and attribute.
>> It just seems so incredibly inconsistent. synchronized encourages doing
>> the wrong thing (locks and synchronization).
>
> It allows multiple approaches at multiple levels. TLS and message passing is
> the preferred way, and shared combined with synchronized or mutexes to protect
> it is available when you need it. synchronized classes are more
> straightforward approach to locking when you need to protect an entire object
> (and less error-prone in some respects, because you then have the guarantee
> that it happens for all functions and don't run the risk of not locking in
> some functions; it also works with inheritance that way, unlike mutexes).
> sychronized blocks on the other hand are a quick and easy way to protect
> specific sections of code without having to bother creating mutexes for it. And
> mutexes are available when you need full control. Which approach you go with
> depends on what you're doing and what your needs are.

I agree on your point about synchronized blocks, but not about 
synchronized classes. Synchronized classes lock on the this reference, 
which is exactly what should be avoided.

>
> Now, I could definitely see an argument that using shared is more low level and
> that it would be just simpler to only have mutexes and no synchronized, but we
> ended up with a more tiered approach, and that's not all bad. Each approach
> has its advantages and disadvantages, and D gives you all of them, so you can
> pick and choose what works best for you.
>
> - Jonathan M Davis

To be clear, I have nothing against synchronized blocks per se. I think 
it's fine to have them in the language. But I think that making *every* 
object a monitor is a horrible mistake (for reasons I outlined in 
another post in this thread). Synchronized blocks are good because they 
operate on an implicit, hidden, global mutex. You can't screw up with that.

Synchronized blocks that operate on a specific object should be limited 
somehow so not every object has to have a monitor field.

-- 
Alex Rønne Petersen
alex at lycus.org
http://lycus.org


More information about the Digitalmars-d mailing list