对局部变量允许C#编译器优化和从内存中重新获取价值 [英] Allowed C# Compiler optimization on local variables and refetching value from memory
问题描述
修改:我问发生了什么,当两个线程的同时访问同一个数据,而不适当的同步(此编辑之前,这一点是不是前pressed明确)。
EDIT: I am asking what happens when two threads concurrently access the same data without proper synchronization (before this edit, that point was not expressed clearly).
我有一个关于是由C#编译器和JIT编译器执行的优化问题。
I have a question about the optimizations that are performed by the C# compiler and by the JIT compiler.
考虑以下简化的例子:
class Example {
private Action _action;
private void InvokeAction() {
var local = this._action;
if (local != null) {
local();
}
}
}
请在本例中忽略读 _action
可能生成缓存和过时的价值,因为没有挥发性的说明,也没有任何其他的同步控制器。这是不是问题的关键:)
Please ignore in the example that reading _action
might yield a cached and outdated value as there is no volatile specifier nor any other sychronization. That is not the point :)
允许优化分配局部变量出来,而不是阅读的编译器(或实际的抖动在运行时) _action
一倍的内存:
Is the compiler (or actually the jitter at runtime) allowed to optimize the assignment to the local variable out and instead reading _action
from memory twice:
class Example {
private Action _action;
private void InvokeAction() {
if (this._action != null) {
this._action(); // might be set to null by an other thread.
}
}
}
这可能会抛出一个的NullReferenceException
当现场 _action
设置为空
由并发任务。
which might throw a NullReferenceException
when the field _action
is set to null
by a concurrent assignment.
当然在本实施例中这样的优化,将没有任何意义,因为它会更快存储该值在寄存器,因此使用局部变量。但在更复杂的情况,有没有保证,这种按预期工作无需从内存中重新阅读的价值?
Of course in this example such an "optimization" would not make any sense because it would be faster to store the value in a register and thus using the local variable. But in more complex cases, is there a guarantee that this works as expected without re-reading the value from memory?
推荐答案
这是根据在ECMA规范中定义的内存模型法律的优化。如果_action是易失性内存模式将保证值只读一次,所以这种优化可能不会发生。
It is legal optimization according to the memory model defined in the ECMA specification. If the _action were volatile, memory model would guarantee that the value is read only once and so this optimization could not happen.
不过,我认为,目前微软的CLR实现不优化局部变量了。
However, I think that current Microsoft's CLR implementations do not optimize local variables away.
这篇关于对局部变量允许C#编译器优化和从内存中重新获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!