In C#, volatile
关键字确保读取和写入分别具有获取和释放语义。但是,它是否说明了有关引入的读取或写入的内容?
例如:
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!
}
Here's what the C# spec1 has to say about Execution Order https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/basic-concepts#execution-order:
C# 程序的执行过程会在关键执行点保留每个执行线程的副作用。 A副作用被定义为对易失性字段的读取或写入...
执行环境可以自由更改 C# 程序的执行顺序,但受以下约束:
...
对于易失性读取和写入,保留了副作用的顺序......
我当然会考虑引入新的副作用改变副作用的顺序,但这里没有明确说明。
答案中的链接是 C# 6 规范,该规范被列为草案。 C# 5 规范不是草案,但无法在线获取,仅作为download https://www.microsoft.com/en-gb/download/details.aspx?id=7029。据我在本节中看到的,相同的措辞。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)