Code example proven to fail w/o volatile

前端 未结 2 607
轻奢々
轻奢々 2021-01-15 13:03

Below is a C# code example which is a verbatim translation of a broken Java code (which has proven to break (i. e. the 2nd thread may fail to observe the change of sha

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 13:36

    This should get stuck in an infinite loop (I can't test it right now)

    public class Test
    {
      private bool loop = true;
    
      public static void Main()
      {
        Test test = new Test();
        Thread thread = new Thread(DoStuff);
        thread.Start(test);
    
        Thread.Sleep(1000);
    
        test.loop = false;
        Console.WriteLine("loop is now false");
      }
    
      private static void DoStuff(object o) {
        Test test = (Test)o;
        Console.WriteLine("Entering loop");
        while (test.loop) {
    
        }
        Console.WriteLine("Exited loop");
      }
    

    }

提交回复
热议问题