LDC optimized builds causing unexpected behaviour when sharing variable between threads
Keivan Shah
keivan.shah at silverleafcaps.com
Wed Jun 1 07:02:08 UTC 2022
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.
More information about the digitalmars-d-ldc
mailing list