Thread.VolatileRead() vs Volatile.Read()

后端 未结 2 1784
名媛妹妹
名媛妹妹 2020-12-12 18:26

We are told to prefer Volatile.Read over Thread.VolatileRead in most cases due to the latter emitting a full-fence, and the former emitting only the relevant half-fence (e.g

2条回答
  •  没有蜡笔的小新
    2020-12-12 18:53

    The Volatile.Read essentially guarantees that read and write operations which occur after it cannot be moved before the read. It says nothing about preventing write operations which occur before the read from moving past it. For example

    // assume x, y and z are declared 
    x = 13;
    Console.WriteLine(Volatile.Read(ref y));
    z = 13;
    

    There is no guarantee that the write to x occurs before the read of y. However the write to z is guaranteed to occur after the read of y.

    // assume x, y and z are declared 
    x = 13;
    Console.WriteLine(Thread.VolatileRead(ref y));
    z = 13;
    

    In this case though you can be guaranteed that the order here is

    • write x
    • read y
    • write z

    The full fence prevents both reads and writes from moving across it in either direction

提交回复
热议问题