I commonly write code that is along these lines:
public class MyClass
{
static bool m_stop = false;
public static void Main()
{
var th = new Thread(DoStuff);
th.Start();
Console.ReadLine();
m_stop = true;
th.Join();
}
private static void DoStuff()
{
while( !m_stop )
{
// do things here
}
}
}
... and I always synchronize access to the variable m_stop, just out of habit. I'm wondering whether it's actually necessary to do that (assuming running an extra loop or two in DoStuff() won't hurt anything). What is the worst that could happen if the code executed exactly like this? I've toyed with the thought of using the volatile keyword for m_stop, but I'm not sure that even that is necessary. Anyone know for sure?