gpt4 book ai didi

c# - 读淘汰与并发

转载 作者:太空狗 更新时间:2023-10-29 22:25:40 25 4
gpt4 key购买 nike

给定以下简单代码:

class Program
{
static bool finish = false;

static void Main(string[] args)
{
new Thread(ThreadProc).Start();
int x = 0;
while (!finish)
{
x++;
}
}

static void ThreadProc()
{
Thread.Sleep(1000);
finish = true;
}
}

并使用 MSVS2015(.NET 4.6) 在 Release 模式下运行它,我们将得到一个永无止境的应用程序。发生这种情况是因为 JIT 编译器生成的代码只读取一次 finish,因此会忽略任何 future 的更新。

问题是:为什么允许 JIT 编译器进行这样的优化?规范的哪一部分允许这样做?

最佳答案

这在 C# Specification 的第 10.5.3 节 - volatile 字段中有所介绍:

(我在下面强调了涵盖您的观察的部分)

10.5.3 Volatile Fields
When a field-declaration includes a volatile modifier, the fields introduced by that declaration are volatile fields.
For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multithreaded programs that access fields without synchronization, such as that provided by the lock-statement (§8.12). These optimizations can be performed by the compiler, by the runtime system, or by hardware. For volatile fields, such reordering optimizations are restricted:
* A read of a volatile field is called a volatile read. A volatile read has “acquire semantics”; that is, it is guaranteed to occur prior to any references to memory that occur after it in the instruction sequence.
* A write of a volatile field is called a volatile write. A volatile write has “release semantics”; that is, it is guaranteed to happen after any memory references prior to the write instruction in the instruction sequence.
These restrictions ensure that all threads will observe volatile writes performed by any other thread in the order in which they were performed. A conforming implementation is not required to provide a single total ordering of volatile writes as seen from all threads of execution.

关于c# - 读淘汰与并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com