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

Artur Skawina art.08.09 at gmail.com
Fri Jun 1 08:51:02 PDT 2012


On 06/01/12 14:26, deadalnix wrote:
> Le 31/05/2012 20:17, Andrei Alexandrescu a écrit :
>> On 5/31/12 5:19 AM, deadalnix wrote:
>>> 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.
>>
>> It can also be a lot clunkier for certain abstractions. Say I want a
>> ProducerConsumerQueue. It's much more convenient to simply make it a
>> synchronized class with the classic primitives, instead of primitives
>> that accept delegates etc.
>>
>> Nevertheless I think there's merit in this idea. One thing to point out
>> is that the idiom can easily be done today with a regular class holding
>> a synchronized class private member.
>>
>> So we got everything we need.
>>
>>
>> Andrei
> 
> I was thinking about that. Here is what I ended up to think is the best solution :
> 
> synchronized classes exists. By default, they can't be use as parameter for synchronized(something) .
> 
> synchronized(something) will be valid is something provide opSynchronized(scope delegate void()) or something similar. Think opApply here. The synchronized statement is rewritten in a call to that delegate.

This has similar issues as opApply. It would have to be a template and
always inlined; The opLock/opUnlock approach lets you do the same things
w/o the delegate overhead and signature restrictions while making it a
bit harder to screw up the locking.

> It open door for stuff like :
> ReadWriteLock rw;
> synchronized(rw.read) {
> 
> }
> 
> synchronized(rw.write) {
> 
> }
> 
> And many types of lock : spin lock, interprocesses locks, semaphores, . . . And all can be used with the synchronized syntax, and without exposing locking and unlocking primitives.
> 
> What do people think ?

It can already be done using 'synchronized', it's *only* an issue
of efficiency and syntax. Eg right now i'm doing

      { scope s = somesemaphore.sync;
         whatever();
      }

and a properly lowered 'synchronized' would turn that into

      synchronized (somesemaphore) {
         whatever();
      }

Currently, the latter is probably possible, but not w/o a huge
perf hit; the former is practically free, just as if it was written
as:
    somesemaphore.wait();
    try whatever();
    finally somesemaphore.post();

Lowering 'synchronized' is about making the second form possible,
for anything resembling some kind of synchronization primitive.
OpSynchronized isn't necessary.

artur 


More information about the Digitalmars-d mailing list