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

Regan Heath regan at netmail.co.nz
Thu May 31 07:39:44 PDT 2012


On Thu, 31 May 2012 15:06:14 +0100, deadalnix <deadalnix at gmail.com> wrote:

> Le 31/05/2012 16:01, Regan Heath a écrit :
>> True, it's basically the same as a synchronized block in that respect.
>> What we actually want is a way to limit the calls made by the delegate
>> to methods of the object itself. If it could not call a synchronized
>> method on a 2nd object, you could not possibly deadlock. Except, that is
>> to say, unless you held a separate lock beforehand - but, the important
>> point here is that you would have to take both locks explicitly, rather
>> than by an implicit synchronized method call, making the bug far more
>> obvious to code inspection.
>>
>> R
>>
>
> I'm not sure I follow you here. Can you elaborate on that ?

Apologies in advance, my D code skillz have rusted significantly..

class A
{
   synchronized void foo()
   {
   }
}

class B {}

void main()
{
   A a = new A();
   B b = new B();

   synchronized(b)  // locks B
   {
     a.foo();       // locks A
   }
}

.. this deadlocks if another thread locks A then B anywhere.  The  
"problem" is that this can be hard to spot and easy to do accidentally as  
a.foo() does not scream "I'm going to lock something".

This is the same problem with the synchronized method calling a supplied  
delegate..

class A
{
   synchronized void foo()
   {
   }
}

class B
{
   synchronized void syncDelegate(void delegate(void) dg) { .. }
}

void main()
{
   A a = new A();
   B b = new B();

   b.syncDelegate(.. code which calls a.foo() .. );  // locks B  
(syncDelegate), then locks A (a.foo)
}

The only way to avoid the deadlock is to prevent calls to synchronized  
methods inside the delegate.

R

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d mailing list