Почему C #volatile protect write -не выполняет переупорядочение чтения?

Согласно этой онлайн-книге , ключевое слово volatileв C #не защищает от переупорядочения операций записи, за которыми следуют операции чтения. Это дает этот пример, в котором aи bмогут в конечном итоге быть установлены на 0, несмотря на то, что xи yравны volatile:

class IfYouThinkYouUnderstandVolatile
{
  volatile int x, y;

  void Test1()        // Executed on one thread
  {
    x = 1;            // Volatile write (release-fence)
    int a = y;        // Volatile read (acquire-fence)
   ...
  }

  void Test2()        // Executed on another thread
  {
    y = 1;            // Volatile write (release-fence)
    int b = x;        // Volatile read (acquire-fence)
   ...
  }
}

. Кажется, это соответствует тому, что говорится в спецификации в 10.5.3 :

A read of a volatile field is called a volatile read. A volatile read has “acquire semantics”; that is, it is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.

A write of a volatile field is called a volatile write. A volatile write has “release semantics”; that is, it is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.

. Что является причиной этого? Есть ли вариант использования, в котором мы не возражаем против изменения порядка операций записи -чтения?

18
задан Eric 31 July 2012 в 19:41
поделиться