LDC optimized builds causing unexpected behaviour when sharing variable between threads

Johan j at j.nl
Wed Jun 1 08:23:18 UTC 2022


On Wednesday, 1 June 2022 at 07:02:08 UTC, Keivan Shah wrote:
> Hello,
> I am encountering a strange bug when making optimized build 
> with LDC. Can someone please help me debug it.
>
> ```
> void main()
> {
>     import std.stdio : writeln;
>     import core.thread;
>
>     // Runinng this code on LDC with `-O` leads to infinite loop
>
>     writeln("Starting...");
>     bool done = false; // Making this `shared` also doesn't work
>     new Thread({ done = true; }).start();
>     while (!done)
>     {
>     } // Wait for done
>     writeln("Done!");
> }
> ```
> The program ends up in an infinite loop if `-O` is passed to 
> LDC and works normally without it. Also works fine in both 
> cases with dmd. I thought this was due to the variable `done` 
> being shared between threads, so I tried marking the variable 
> as `shared` but even that does not solve the problem. Also 
> tried making the variable global and using `__gshared` doesn't 
> seem to work as well. Finally I was able to solve the problem 
> by using 
> [core.volatile](https://dlang.org/phobos/core_volatile.html), 
> but that doesn't look like a very great solution. So I wanted 
> to understand the main problem here and make sure and also 
> verify that this is not a LDC bug.

This is not a bug.
The solution with `volatileLoad` works, but I think it 
technically isn't quite correct; documentation says: "They should 
not be used for communication between threads.".

There are many articles online about this kind of conditional 
loop on a variable that is modified by another thread. For 
example: 
https://stackoverflow.com/questions/10091112/using-a-global-variable-to-control-a-while-loop-in-a-separate-thread  and  https://devblogs.microsoft.com/oldnewthing/20180924-00/?p=99805

-Johan



More information about the digitalmars-d-ldc mailing list