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

deadalnix deadalnix at gmail.com
Thu May 31 05:19:00 PDT 2012


Le 31/05/2012 13:13, Andrei Alexandrescu a écrit :
> On 5/31/12 3:27 AM, Regan Heath wrote:
>> I think
>> the mutex is "available for locking and unlocking" <- need a word for
>> that, which is not "exposed". How about accessible, available, usable,
>> or just plain lockable .. So, the problem here is that the mutex is
>> lockable by external code via synchronized() and this means a certain
>> type of deadlock is possible.
>
> But this is a protection/visibility issue, which is orthogonal on the
> locking capability. It's as if you say "int is not good because anyone
> can overflow it." Okay! Make it private inside a CheckedInt class.
>
>> Moving on..
>>
>> I think the change mentioned in TDPL to restrict synchronized to
>> synchronized classes is a step in the right direction WRT wasted monitor
>> space and people freely locking anything. But, it is exactly the case
>> which results in more possible deadlocks (the cause of this thread) AND
>> I think it's actually far more likely people will want to use a
>> synchronized statement on a class which is not itself synchronized, like
>> for example an existing container class.
>>
>> Given that, restricting synchronized statements to synchronized classes
>> seems entirely wrong to me.
>
> So where's the mutex that would be used to synchronize objects that are
> not synchronizable?
>
>> In fact, I would say you almost want to stop
>> people using synchronized statements on synchronized classes because:
>> 1. If a synchronized class is written correctly it should not be
>> necessary in the general case(*)
>> 2. It raises the chances of deadlocks (the cause of this thread).
>> 3. It means that classes in general will be simpler to write (no need to
>> worry about synchronization) and also more lightweight for use in
>> non-threaded/non-shared cases. (because we'd provide a template wrapper
>> to make them synchronizable)
>
> There are cases in which you want to do multiple operations under a
> single critical section, even though the API is otherwise well-designed.
> That may be for correctness, efficiency, or both. I don't see why we'd
> want to disallow that, it's a good idiom.
>

Because it is now unclear who is controlling the lock.

The solution consisting in passing a delegate as parameter or as 
template is superior, because it is now clear who is in charge of the 
synchronization, reducing greatly chances of deadlock.


More information about the Digitalmars-d mailing list