While loop on global variable optimised away?
ichneumwn
idonotenjoyemail at idonotenjoyemail.org
Wed May 11 09:34:20 UTC 2022
Hi Forum,
I have a snippet of code as follows:
```
extern(C) extern __gshared uint g_count;
// inside a class member function:
while(g_count) <= count) {}
```
This is from a first draft of the code without proper thread
synchronisation. The global variable g_count is updated from a
bit of C++ code. As soon as I turn the optimiser on, the code
never gets passed this point, leading me to suspect it gets
turned into
```
while(true) {}
```
If modify the code in the following way:
```
import core.volatile : volatileLoad;
while(volatileLoad(&g_count) <= count) {}
```
it works again.
My question is, have I hit a compiler bug (ldc 1.28.1, aarch64
[Raspberry Pi]) or is this part of the language design. I would
have thought since D use thread-local storage by default, that
for a __gshared variable it would be understood that it can get
modified by another thread. Access through atomic function would
prevent the compiler from optimising this away as well, but if I
were to use a Mutex inside the loop, there is no way for the
compiler to tell *what* that Mutex is protecting and it might
still decide to optimise the test away (assuming that is what is
happening, did not attempt to look at the assembler code).
Cheers
More information about the Digitalmars-d-learn
mailing list