Alex Rivera | Logout

Can a C# thread really cache a value and ignore changes to that value on other threads?

Asked 2009-01-19T16:20:43.493
29

This question is NOT about race-conditions, atomicity, or why you should use locks in your code. I already know about those.

UPDATE: My question isn't "does weirdness with volatile memory exist" (i know it does), my question is "doesn't the .NET runtime abstract that away so you'll never see it".

See http://www.yoda.arachsys.com/csharp/threads/volatility.shtml and the first answer on Is a string property itself threadsafe?

(They're really the same article since one references the other.) One thread sets a bool and the other thread loops forever reading that bool -- those articles claim the reading thread might cache the old value and never read the new value, so therefore you need a lock (or use the volatile keyword). They claim the following code will potentially loop forever. Now I agree it's good practice to lock your variables, but I can't believe the .NET runtime would really ignore a memory value changing as the article claims. I understand their talk about volatile memory vs non-volatile memory, and I agree they have a valid point in non-managed code, but I can't believe the .NET runtime won't correctly abstract that away so that the following code does what you expect. The article even admits the code will "almost certainly" work (though not guaranteed), so I'm calling BS on the claim. Can anyone verify that it's true the following code won't always work? Is anyone able to get even one case (maybe you can't always reproduce it) where this fails?

class BackgroundTaskDemo
{
    private bool stopping = false;

    static void Main()
    {
        BackgroundTaskDemo demo = new BackgroundTaskDemo();
        new Thread(demo.DoWork).Start();
        Thread.Sleep(5000);
        demo.stopping = true;
    }

    stat
Edit
Report

2 Answers

5

This example includes the native x86 code as comments to demonstrate that the controlling variable ('stopLooping') is cached.

Change 'stopLooping' to volatile to "fix" it.

This was built with Visual Studio 2008 as a Release build and run without debugging.

 using System;

 using System.Threading;

/* A simple console application which demonstrates the need for 
 the volatile keyword and shows the native x86 (JITed) code.*/

static class LoopForeverIfWeLoopOnce
{

    private static bool stopLooping = false;

    static void Main()
    {
        new Thread(Loop).Start();
        Thread.Sleep(1000);
        stopLooping = true;
        Console.Write("Main() is waiting for Enter to be pressed...");
        Console.ReadLine();
        Console.WriteLine("Main() is returning.");
    }

    static void Loop()
    {
        /*
         * Stack frame setup (Native x86 code):
         *  00000000  push        ebp  
         *  00000001  mov         ebp,esp 
         *  00000003  push        edi  
         *  00000004  push        esi  
         */

        int i = 0;
        /*
         * Initialize 'i' to zero ('i' is in register edi)
         *  00000005  xor         edi,edi 
         */

        while (!stopLooping)
            /*
             * Load 'stopLooping' into eax, test and skip loop if != 0
             *  00000007  movzx       eax,byte ptr ds:[001E2FE0h] 
             *  0000000e  test        eax,eax 
             *  00000010  jne         00000017 
             */
        {
            i++;
            /*
             * Increment 'i'
             *  00000012  inc         edi  
             */

            /*
             * Test the cached value of 'stopped' still in
             * register eax and do it again if it's still
             * zero (false), which it is if we get here:
             *  00000013  test        eax,eax 
             *  00000015  je          00000012 
             */
        }

        Console.WriteLine("i={
answered 2009-01-19T17:42:23.827
3

FWIW:

  • I have seen this compiler optimization from the MS C++ compiler (unmanaged code).
  • I don't know whether it happens in C#
  • It won't happen while debugging (compiler optimizations are automatically disabled while debugging)
  • Even if that optimization doesn't happen now, you're betting that they'll never introduce that optimization in future versions of the JIT compiler.
answered 2009-01-19T16:29:04.473

Your Answer