根据这本在线书籍,volatileC#中的关键字不能防止重新排序Write操作,然后是Read操作.它给出了这样的例子,其中两个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)
...
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎符合10.5.3规范中的内容:
读取volatile字段称为volatile读取.易失性读取具有"获取语义"; 也就是说,保证在指令序列之后发生的任何内存引用之前发生.
写入易失性字段称为易失性写入.易失性写入具有"释放语义"; 也就是说,保证在指令序列中的写指令之前的任何存储器引用之后发生. …