thread-safe shared field access

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 30 07:25:06 PDT 2016


On 6/30/16 10:10 AM, jj75607 wrote:
> For example I have a shared from different threads variable. What piece
> of code is correctly thread-safe?
>
> First:
>   shared class A
>   {
>       shared(int) x;

Note, no need to mark x shared. 'A' implicitly shares everything.

>
>       void test1()
>       {
>           x = 10;
>           x += 5
>           writeln(x);
>       }
>   }
>
> Or second:
>   import core.atomic;
>   shared class A
>   {
>       shared(int) x;
>
>       void test1()
>       {
>           atomicStore(x, 10);
>           atomicOp!("+=")(x, 5);
>           writeln(atomicLoad(x));
>       }
>   }

I don't believe the first will compile. This is probably the only thing 
that D adds for shared data (it enforces that you use atomics to read or 
modify shared primitives). And yes, the second is correct while the 
first is not.

Note that writeln is still writing a copy of the atomically loaded x. 
you could as easily done:

auto xcopy = atomicOp!("+=")(x, 5);
writeln(xcopy);

To avoid the atomic load.

-Steve


More information about the Digitalmars-d-learn mailing list