Two threads (main thread and another thread called T) have access to the same boolean field. T does nothing but while (_bool) { }
and Main assigns false to _bool
after 2 seconds.
On Debug, T exits the loop.
On Release, T never exits the loop.
Why?
EDIT:
Moreover, why volatile
on _bool
solves this?
using System;
using System.Threading;
namespace ConsoleApplication1
{
internal class Program
{
private bool _bool = true;
private static void Main()
{
var program = new Program();
var t = new Thread(SomeThread);
t.Start(program);
Thread.Sleep(2000);
program._bool = false;
Console.WriteLine(program._bool);
}
private static void SomeThread(object obj)
{
var p = obj as Program;
Console.WriteLine("Entered loop");
while (p._bool)
{
}
Console.WriteLine("Exited Loop");
}
}
}