.NET多线程,挥发性记忆模型 [英] .NET multithreading, volatile and memory model

查看:118
本文介绍了.NET多线程,挥发性记忆模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有下面的代码:

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;
    }
  }
}



它的错!主要quastion是为什么......我想与FLAG1 =诚然,CPU重新排序操作;如果(FLAG2)语句,但变量FLAG1 FLAG2和标记为挥发性场...

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...

推荐答案

在.NET内存模型时,运行时(CLI),将确保挥发字段更改不会在寄存器缓存,所以在任何线程的变化被立刻看到的其他线程( NB 的,这不是在其他存储器模型,包括真Java的)。

In the .NET memory model, the runtime (CLI) will ensure that changes to volatile fields are not cached in registers, so a change on any thread is immediately seen on other threads (NB this is not true in other memory models, including Java's).

不过,这并未提及业务跨多个相对顺序,挥发性与否,字段。

But this says nothing about the relative ordering of operations across multiple, volatile or not, fields.

要提供跨越需要(显式或隐式或一个存储器屏障,具有包括一个存储器屏障的方法之一)使用锁多个字段一致的排序。

To provide a consistent ordering across multiple fields you need to use a lock (or a memory barrier, either explicitly or implicitly with one of the methods that include a memory barrier).

有关详细信息,请参见在Windows并发编程,乔·达菲,AW,2008

For more details see "Concurrent Programming on Windows", Joe Duffy, AW, 2008

这篇关于.NET多线程,挥发性记忆模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆