在方法开头使用 Volatile.Write 的原因

Reason for using Volatile.Write at the beginning of a method

我想我有点明白 Volatile.WriteVolatile.Read 到底做了什么,但是我看到了一些例子,其中 Volatile.Write 在方法的开头使用,例如通过 C# 实现 CLR 的书,其中 Jeffrey 展示了如何使用 Interlocked 实现简单自旋锁。这是代码:

struct SimpleSpinLock {
   private int _resourceInUse; // 0 = false, 1 = true

   public void Enter() {
      while (true) {
         if (Interlocked.Exchange(ref _resourceInUse, 1) == 0) return;
      }
   }

   public void Leave() {
      Volatile.Write(ref _resourceInUse, 0); // Why is it here??
   }
}

class 应该这样使用:

class SomeResource {
   private SimpleSpinLock _s1 = new SimpleSpinLock();

   public void AccessResource() {
      _s1.Enter();
      // Some code that only one thread at a time can get in..
      _s1.Leave();
   }
}

据我所知,Volatile.Write 用于保证其上方的指令将在 Volatile.Write 之前执行。但是在Leave方法中只有一条指令,这里使用Volatile.Write的原因是什么?可能我理解的东西完全错误,所以如果有人能引导我走上正确的道路,我将不胜感激。

不会声称我有足够的脑力来完全 understand/explain 这个,但这是我的 5 美分。首先,编译器可以内联 Leave 方法调用,因为它只包含一行,所以实际写入可以被其他指令包围。其次(我想主要是)Volatile class docs 状态接下来:

On a multiprocessor system, a volatile write operation ensures that a value written to a memory location is immediately visible to all processors.

所以此 Volatile.Write 调用的目标是尽快让其他处理器看到更改。

另请参阅 question and read about volatile keyword

的答案

Volatile.Write

"Writes a value to a field. On systems that require it, inserts a memory barrier that prevents the processor from reordering memory operations as follows: If a read or write appears before this method in the code, the processor cannot move it after this method."

我的理解是:

这句话所指的方法是Volatile.Write()。所以,"if a read or write operation appears before Volatile.Write in the code, the processor cannot move it after Volatile.Write"。这意味着如果另一个线程(例如)在同一资源上 reading/writing,则它必须等待 Volatile.Write 执行后才能被处理器调度。

这很有道理,不是吗?我不认为这是 read/write 指令在 "hosting" 方法(离开)中的位置问题,而是更多关于 Enter 和 Leave 之间的 read/writes "happening"。