I'm studying c# threading following famous 'C# in a Nutshell' and during investigation of Thread.MemoryBarrier() phenomena, I was scared to death when I stumbled upon Brian's example on Why we need Thread.MemoryBarrier()?.
I'm having i-7 8700K processor and 4.6.1 .NET and I managed to reproduce the problem (program never ends) even with following changes in program:
class Program
{
static bool stop = false;
public static void Main(string[] args)
{
var t = new Thread(() =>
{
Console.WriteLine($"Thread begin");
bool toggle = false;
//while (true)
while (!stop)
{
if (stop)
{
break;
}
toggle = !toggle;
}
Console.WriteLine($"Thread end");
});
t.Start();
Thread.Sleep(1000);
stop = true;
Console.WriteLine($"Stop flag set. Waiting for thread to end...");
t.Join();
Console.ReadKey();
}
}
So, even with "if (stop)" check, problem reproduces and I understand why. When I place "Thread.MemoryBarrier()" before that check problem doesn't reproduce (at least I failed to reproduce it) and I understand why. But what I don't understand is why problem is not reproducing anymore when I change while condition and put "while (true)" instead of "while (!stop)"? Does it have something to do with special treatment of "while (true)" statement?