#604 – The Problem with Reading/Writing Shared Data from Different Threads

Reading shared data from a thread different to the one where you wrote the data, you may see unexpected results.  Consider the following:

    public class Program
    {
        public static bool runFlag = true;

        private static void RunUntilYouStopMe()
        {
            int i = 0;

            while (runFlag)
            {
                i++;
            }

            Console.WriteLine("I'm stopping");
        }

        static void Main()
        {
            Thread runThread = new Thread(new ThreadStart(RunUntilYouStopMe));
            runThread.Start();

            Thread.Sleep(1000);

            runFlag = false;
            Console.WriteLine("Main() has set runFlag to false");

            while (true)
            {
                Console.ReadLine();
                Console.WriteLine(".. runThread.IsAlive={0}", runThread.IsAlive);
            }
        }
    }

The background thread should run until the runFlag variable gets set to false.  We start the background thread and then set the flag to false on the main thread.  But running this code in Release|x86 mode, it turns out that the loop never exits, even though we set runFlag to false.

This is caused by a compiler optimization related to our runFlag variable.