[dmd-concurrency] synchronized, shared, and regular methods inside the same class

Andrei Alexandrescu andrei at erdani.com
Mon Jan 4 16:12:59 PST 2010


Sean Kelly wrote:
>>> So if I have:
>>>    class A
>>>    {
>>>        void fn() shared { x = 5; }
>>>        int x;
>>>    }
>>> Is this legal?  If the type of the object doesn't change then I'd guess that I won't be allowed to access non-shared fields inside a shared function?
>> Shared automatically propagates to fields, so typeof((new shared(A)).x) is shared int. Of course that's not the case right now; the typeof expression doesn't even compile :o).
> 
> Hm... but what if fn() were synchronized instead of shared?  Making x shared in that instance seems wasteful.  I had thought that perhaps a shared function would simply only be allowed to access shared variables, and possibly call synchronized functions:
> 
>     class A {
>         void fnA() shared { x = 5; } // ok, x is shared
>         void fnB() shared { y = 5; } // not ok, y is not shared
>         void fnC() synchronized { y = 5; } // ok, non-shared ops are ok if synchronized
>         shared int x;
>         int y;
>     }

Aha! You've just discovered the tail-shared exemption: inside a 
synchronized method, direct fields can be accessed without barriers 
(neither implicit or explicit) although technically their type is still 
shared. Fortunately the compiler has all the information it needs to 
elide those barriers.


Andrei



More information about the dmd-concurrency mailing list