www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is comparison of shared data thread-safe?

reply Nick Treleaven <nick geany.org> writes:
With -preview=nosharedaccess, I get:

     int y = 2;
     shared int x = y; // OK

     assert(x == 2); // no error
     y = x; // error

So for the assignment to y, reading x is an error and atomicLoad 
should be used instead. But is it an oversight that reading x in 
the assert is not an error?

I have also found this in a unittest in core.atomic:

         shared(size_t) i;

         atomicOp!"+="(i, cast(size_t) 1);
         assert(i == 1);

Is the assert somehow thread-safe?
Mar 16 2023
next sibling parent Nick Treleaven <nick geany.org> writes:
On Thursday, 16 March 2023 at 12:32:34 UTC, Nick Treleaven wrote:
 With -preview=nosharedaccess, I get:

     int y = 2;
     shared int x = y; // OK

     assert(x == 2); // no error
     y = x; // error
This also does not error: ```d bool b = x == 3; ``` Filed: https://issues.dlang.org/show_bug.cgi?id=23783
Mar 16 2023
prev sibling parent bauss <jacobbauss gmail.com> writes:
On Thursday, 16 March 2023 at 12:32:34 UTC, Nick Treleaven wrote:
 With -preview=nosharedaccess, I get:

     int y = 2;
     shared int x = y; // OK

     assert(x == 2); // no error
     y = x; // error

 So for the assignment to y, reading x is an error and 
 atomicLoad should be used instead. But is it an oversight that 
 reading x in the assert is not an error?

 I have also found this in a unittest in core.atomic:

         shared(size_t) i;

         atomicOp!"+="(i, cast(size_t) 1);
         assert(i == 1);

 Is the assert somehow thread-safe?
I think it __should__ be fine since `i` cannot be in a state where it gets modified and read at the same time.
Mar 17 2023