How does Interlocked.MemoryBarrierProcessWide() change the execution order in multicore?

26 views Asked by At

if we run the below code with release mode

class Program
{
    static volatile int x, y, a, b;
    static void Main()
    {
        while (true)
        {
            var t1 = Task.Run(Test1);
            var t2 = Task.Run(Test2);
            Task.WaitAll(t1, t2);
            if (a == 0 && b == 0)
            {
                Console.WriteLine("{0}, {1}", a, b);
            }
            x = y = a = b = 0;
        }
    }

    static void Test1()
    {
        x = 1; 
        //Interlocked.MemoryBarrierProcessWide()   comment out first
        a = y;
    }

    static void Test2()
    {
        y = 1;
        b = x;
    }
}

we can see a lot of 0,0 printed because we dont' use any memory barrier. However, if we use Interlocked.MemoryBarrierProcessWide() (uncomment it), then we won't see any 0,0 output.

However, if I change the order in Test2 as

class Program
{
    static volatile int x, y, a, b;
    static void Main()
    {
        while (true)
        {
            var t1 = Task.Run(Test1);
            var t2 = Task.Run(Test2);
            Task.WaitAll(t1, t2);
            if (a == 0 && b == 0)
            {
                Console.WriteLine("{0}, {1}", a, b);
            }
            x = y = a = b = 0;
        }
    }

    static void Test1()
    {
        x = 1;   // 2
        Interlocked.MemoryBarrierProcessWide();  // 3
        a = y;   // 4
    }

    static void Test2()
    {

        b = x;   // 1

        y = 1;   // 5
    }
}

I mark the execution order, threadA execute 1, so b is 0, then a context switch happens threadB execute 2,3,4, and after 4 is executed, a is 0, then threadA continute to execute 5. so we should be getting 0,0 printed but there is none, why is that? how does Interlocked.MemoryBarrierProcessWide() change the execution order so that no 0,0 printed regardsless of Test2 being

static void Test2()
{
   y = 1;
   b = x;
}

or

static void Test2()
{
   b = x;
   y = 1;   
}
0

There are 0 answers