Very limited shared promotion

Manu turkeyman at gmail.com
Thu Jun 20 06:53:05 UTC 2019


On Wed, Jun 19, 2019 at 7:15 PM Walter Bright via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
>
> On 6/17/2019 4:46 PM, Manu wrote:
> > Is this valid?
> >
> > int x;
> > void fun(scope ref shared(int) x) { ... }
> > fun(x); // implicit promotion to shared in this case
> >
> > This appears to promote a thread-local to shared. The problem with
> > such promotion is that it's not valid that a thread-local AND a shared
> > reference to the same thing can exist at the same time.
> >
> > With scope, we can guarantee that the reference doesn't escape the callee.
> > Since the argument is local to the calling thread, and since the
> > calling thread can not be running other code at the same time as the
> > call is executing, there is no way for any code to execute with a
> > thread-local assumption while the callee makes shared assumptions.
> >
> > I think this might be safe?
> >
>
> Using the resulting value of x:
>
>    int x;
>    void fun(scope ref shared(int) x) { ... }
>    fun(x); // implicit promotion to shared in this case
>    int y = x; // add this line
>
> And now there's a problem. The compiler thinks x is thread local, so it doesn't
> add synchronization to the read of x. Not adding synchronization means that
> although fun() has terminated all the threads it spawned accessing x, it does
> not mean the memory caches of x are updated.
>
> While you may have coded fun() to update the caches of x before returning, the
> compiler can't know that, and so the compiler cannot allow the implicit conversion.
>
> In other words, adding `scope` does not guarantee SC-DRF (Sequential Consistency
> - Data Race Free).

Well, you're assuming that `fun()` is an unsafe function that did
violate the scope agreement and passed it out to worker threads. *ANY*
deployment of @trusted code requires that you know what you're doing.
So, rather, let's assume that fun() does NOT do that, and it is in
fact @safe... your concern does not arise in that world where you're
not manually violating the type system.

So the issue you describe is only possible where you have deliberately
written unsafe code to perform a very low-level operation. You're
obviously incompetent if you don't implement the sequential
consistency machinery at the conclusion of your low-level machine.
I don't think saying "this person wasn't qualified to implement a
@trusted function" is a valid reason to reject an extremely useful
improvement.

TL;DR: I don't think your argument is valid. If it were, you would
have to apply that reasoning to every @trusted function out there.
Language features are not required to consider that a @trusted author
may make a mistake; that is literally the point of @trusted.


More information about the Digitalmars-d mailing list