Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can AC be used for heat?

The reality is that many air conditioning units can also be used to heat rooms. There are air conditioning systems on the market which can keep rooms warm in the winter, and cooler in the summer.

How many cans of AC Pro do I need?

Most cars hold between 28 and 32 ounces of refrigerant (or about 2—3 12oz cans), however larger vehicles and those with rear A/C will likely hold more. Check your vehicle manual for the system capacity for your specific vehicle.

Does AC mean cold or hot air?

Your air conditioner does not “create” cold air, it removes heat from warm air. So, how does your air conditioner remove the heat from the air in your home? The Air Conditioning, Heating and Refrigeration Institute (AHRI) describes how this works in great detail.

Does AC Pro have oil in it?

A/C Pro contains compressor oil, but it's the type used in regular belt-driven A/C systems.


The point is: it might work, but it isn't guaranteed to work by the spec. What people are usually after is code that works for the right reasons, rather than working by a fluke combination of the compiler, the runtime and the JIT, which might change between framework versions, the physical CPU, the platform, and things like x86 vs x64.

Understanding the memory model is a very very complex area, and I don't claim to be an expert; but people who are real experts in this area assure me that the behaviour you are seeing is not guaranteed.

You can post as many working examples as you like, but unfortunately that doesn't prove much other than "it usually works". It certainly doesn't prove that it is guaranteed to work. It would only take a single counter-example to disprove, but finding it is the problem...

No, I don't have one to hand.


Update with repeatable counter-example:

using System.Threading;
using System;
static class BackgroundTaskDemo
{
    // make this volatile to fix it
    private static bool stopping = false;

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


        Console.WriteLine("Main exit");
        Console.ReadLine();
    }

    static void DoWork()
    {
        int i = 0;
        while (!stopping)
        {
            i++;
        }

        Console.WriteLine("DoWork exit " + i);
    }
}

Output:

Main exit

but still running, at full CPU; note that stopping has been set to true by this point. The ReadLine is so that the process doesn't terminate. The optimization seems to be dependent on the size of the code inside the loop (hence i++). It only works in "release" mode obviously. Add volatile and it all works fine.


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={0}", i);
    }
}

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.