shared - i need it to be useful

Manu turkeyman at gmail.com
Mon Oct 15 19:33:48 UTC 2018


On Mon, Oct 15, 2018 at 12:15 PM Peter Alexander via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
>
> On Monday, 15 October 2018 at 18:46:45 UTC, Manu wrote:
> > 2. object may have shared methods; such methods CAN be called on
> > shared instances. such methods may internally implement
> > synchronisation to perform their function. perhaps methods of a
> > lock-free queue structure for instance, or operator overloads on
> > `Atomic!int`, etc.
>
> Just checking my understanding: are you saying here that shared
> methods can effectively do anything and the burden of correctness
> is on the author? Or do you still have to cast the shared away
> first?

Burden of correctness that a `shared` method is indeed threadsafe is
absolutely on the author; there's nothing we can do to guarantee this
(multithreading is hard!), but in this new world, a user of an API
will be able to see shared methods and assume that they're threadsafe,
since that would be (and should be!) the whole point.

Since `shared` has no read or write access, at the bottom of the
stack, it may be necessary that the function cast shared away to
implement its magic. If you lock a mutex for instance, then you
naturally need to cast it away; but that's solving the problem with a
sledge-hammer.
In my experience, most such functions are implemented with atomics;
and the atomic API already receives shared args, ie:
https://github.com/dlang/druntime/blob/master/src/core/atomic.d#L379
So, if you do your work with atomics, then you don't need any casts.
Also, if the object is a composite, then a `shared` method is able to
call `shared` methods on its members, and in that case, you are able
to do useful aggregate work without casting.

I think the interactions I describe above are all correct.


More information about the Digitalmars-d mailing list