#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

  1. polkduran says:

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

    Could you be more explicit please ?
    What would be the solution ?

    Thanks

    • Sean says:

      Good question–answer coming up in tomorrow’s post. Also some explanation as to what’s going on. If you want to read ahead, go do some googling on “volatile” keyword in C#.

  2. Pingback: #605 – The Causes of Problems With Reading/Writing Shared Data from Multiple Threads « 2,000 Things You Should Know About C#

  3. Pingback: #606 – Use volatile Keyword to Fix Problems With Reading/Writing Shared Data « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: