.NET multithreading, volatile and memory model

Posted by fedor-serdukov on Stack Overflow See other posts from Stack Overflow or by fedor-serdukov
Published on 2010-04-15T11:51:20Z Indexed on 2010/04/15 12:43 UTC
Read the original article Hit count: 266

Filed under:
|
|
|

Assume that we have the following code:

class Program
 {
    static volatile bool flag1;
    static volatile bool flag2;
    static volatile int val;
    static void Main(string[] args)
    {
      for (int i = 0; i < 10000 * 10000; i++)
      {
        if (i % 500000 == 0)
        {
          Console.WriteLine("{0:#,0}",i);
        }

        flag1 = false;
        flag2 = false;
        val = 0;

        Parallel.Invoke(A1, A2);

        if (val == 0)
          throw new Exception(string.Format("{0:#,0}: {1}, {2}", i, flag1, flag2));
      }
    }

    static void A1()
    {
      flag2 = true;
      if (flag1)
        val = 1;
    }
    static void A2()
    {
      flag1 = true;
      if (flag2)
        val = 2;
    }
  }
}

It's fault! The main quastion is Why... I suppose that CPU reorder operations with flag1 = true; and if(flag2) statement, but variables flag1 and flag2 marked as volatile fields...

© Stack Overflow or respective owner

Related posts about .NET

Related posts about volatile