volatile是否会阻止引入的读取或写入操作? [英] Does volatile prevent introduced reads or writes?

查看:92
本文介绍了volatile是否会阻止引入的读取或写入操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,关键字volatile确保读取和写入分别具有获取和释放语义.但是,它对引入的读取或写入没有说什么吗?

In C#, volatile keyword ensures that reads and writes have acquire and release semantics, respectively. However, does it say anything about introduced reads or writes?

例如:

volatile Thing something;
volatile int aNumber;

void Method()
{
    // Are these lines...
    var local = something;
    if (local != null)
        local.DoThings();

    // ...guaranteed not to be transformed into these by compiler, jitter or processor?
    if (something != null)
        something.DoThings(); // <-- Second read!



    // Are these lines...
    if (aNumber == 0)
        aNumber = 1;

    // ...guaranteed not to be transformed into these by compiler, jitter or processor?
    var temp = aNumber;
    if (temp == 0)
        temp = 1;
    aNumber = temp; // <-- An out-of-thin-air write!
}

推荐答案

这是C#规范 1 关于

继续执行C#程序,以使每个执行线程的副作用都保留在关键执行点上. 副作用定义为对易失性字段的读取或写入...

Execution of a C# program proceeds such that the side effects of each executing thread are preserved at critical execution points. A side effect is defined as a read or write of a volatile field ...

执行环境可以自由更改C#程序的执行顺序,但要遵守以下约束:

The execution environment is free to change the order of execution of a C# program, subject to the following constraints:

...

关于易失性读写,保留了副作用的顺序...

The ordering of side effects is preserved with respect to volatile reads and writes ...

我当然会认为引入新的副作用会改变副作用的顺序,但此处并未明确指出.

I would certainly consider introducing new side effects to be changing the order of side effects, but it's not explicitly stated like that here.

答案中的链接是C#6规范,该规范列为草稿". C#5规范不是草案,但不能在线使用,只能作为下载.就本节中所见,措词完全相同.

Link in answer is to the C# 6 spec which is listed as Draft. C# 5 spec isn't a draft but is not available on-line, only as a download. Identical wording, so far as I can see in this section.

这篇关于volatile是否会阻止引入的读取或写入操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆