【问题标题】:Atomic read-modify-write in C#C#中的原子读-修改-写
【发布时间】:2011-01-11 19:36:18
【问题描述】:

我看到几个地方引用了 C# 规范的以下部分:“除了为此目的设计的库函数之外,不能保证原子读取-修改-写入。”有人可以指出这些库函数吗?

【问题讨论】:

    标签: c# .net multithreading concurrency


    【解决方案1】:

    Interlocked 类应该为您提供所需的内容;比如IncrementDecrement

    【讨论】:

      【解决方案2】:

      我认为是指Interlocked.CompareExchange等函数。

      此方法可用于例如以原子方式更新double

      static void Add(ref double field, double amount)
      {
          double before, after;
          do
          {
              before = field;
              after = before + amount;
          }
          while (Interlocked.CompareExchange(ref field, after, before) != before);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 1970-01-01
        • 2011-01-16
        • 2010-09-08
        • 2011-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多