Given the following class:
class C
{
public int x = 0;
public void F() {
new Thread(G).Start();
while (x == 0) { Thread.Sleep(TimeSpan.FromMilliseconds(1)); }
}
public void G() {
Thread.Sleep(TimeSpan.FromMilliseconds(1000));
Interlocked.Exchange(ref x, 1);
}
}
I assume it is allowed under the C#
standard for new C().F()
to run forever yes, because there's nothing to force F()
to retrieve the value of x
from main memory each access. The Interlocked.Exchange
here even doesn't help, as F()
doesn't see the implementation of G()
so may optimise away the access from main memory.
Is this analysis correct?
Furthermore, I understand making x
volatile will resolve this, but is there anything else that would resolve this issue?