LDC optimized builds causing unexpected behaviour when sharing variable between threads

Johan j at j.nl
Thu Jun 2 11:56:07 UTC 2022


On Thursday, 2 June 2022 at 04:33:39 UTC, Keivan Shah wrote:
> On Wednesday, 1 June 2022 at 16:46:51 UTC, kinke wrote:
>> On Wednesday, 1 June 2022 at 13:35:45 UTC, Keivan Shah wrote:
>>> probably will use 
>>> [core.atomic.atomicFence](https://dlang.org/phobos/core_atomic.html#.atomicFence) to ensure the memoryOrdering.
>>
>> `core.atomic.atomic{Load,Store}` handle this:
>>
>> ```
>> void main()
>> {
>>     import std.stdio : writeln;
>>     import core.thread;
>>     import core.atomic;
>>
>>     writeln("Starting...");
>>     shared bool done = false;
>>     new Thread({ atomicStore(done, true); }).start();
>>     while (!atomicLoad(done))
>>     {
>>     } // Wait for done
>>     writeln("Done!");
>> }
>> ``
>
> Hey kinke,
> Thanks for the snippet, I have some existing code that follows 
> the pattern similar to the example I had given. There are a lot 
> of variables that are shared between the 2 threads and so 
> instead of changing the reads and writes for every variable to 
> be `atomic{Store,Load}`, I was thinking if `atomicFence` might 
> achieve the same effect with far lesser code change 
> requirements. Would that be recommended or should I use 
> `atomic{Store,Load}` instead?

`atomicFence` only works for ordering memory operations on a 
single thread, not ordering between threads.

You can either use a mutex (to coordinate between threads), or 
need all store/loads to be atomic with `atomic{Store,Load}`.
I am surprised that there is no `core.atomic!int` to simplify 
your life. Perhaps you should make a feature request :)

-Johan



More information about the digitalmars-d-ldc mailing list