#606 – Use volatile Keyword to Fix Problems With Reading/Writing Shared Data

When you read data from one thread but write the data from a different thread, you can run into a problem where the thread reading the data will read stale/incorrect data.

You can prevent this behavior by marking the data field in question with the volatile keyword.  This indicates to the compiler that no optimizations should be done with respect to the storage location of this field and will prevent the problem of reading stale data.

Below is the earlier example, updated to include the volatile keyword.

        public static volatile bool runFlag = true;

        private static void RunUntilYouStopMe()
            int i = 0;

            while (runFlag)

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

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


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

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

Before the fix:

After the fix:


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Connecting to %s

%d bloggers like this: