gpt4 book ai didi

C# 编译器优化和 volatile 关键字

转载 作者:行者123 更新时间:2023-11-30 13:31:53 25 4
gpt4 key购买 nike

我读过一些关于 volatile 关键字和没有这个关键字的行为的帖子。

我特别测试了 Illustrating usage of the volatile keyword in C# 的答案中的代码.运行时,我在 Release模式下观察到异常行为,没有附加调试器。到目前为止,没有问题。

因此,据我所知,以下代码永远不会退出。

public class Program
{
private bool stopThread;

public void Test()
{
while (!stopThread) { } // Read stopThread which is not marked as volatile
Console.WriteLine("Stopped.");
}


private static void Main()
{
Program program = new Program();

Thread thread = new Thread(program.Test);
thread.Start();

Console.WriteLine("Press a key to stop the thread.");
Console.ReadKey();

Console.WriteLine("Waiting for thread.");
program.stopThread = true;

thread.Join(); // Waits for the thread to stop.
}
}

为什么会退出?即使在 Release模式下,没有调试器?

更新

改编自 Illustrating usage of the volatile keyword in C# 的代码.

private bool exit;

public void Test()
{
Thread.Sleep(500);
exit = true;
Console.WriteLine("Exit requested.");
}

private static void Main()
{
Program program = new Program();

// Starts the thread
Thread thread = new Thread(program.Test);
thread.Start();

Console.WriteLine("Waiting for thread.");
while (!program.exit) { }
}

在没有附加调试器的情况下,此程序在处于 Release模式后不会退出。

最佳答案

So, as far as I understand, the following should never exit.

不,它可以停止。只是不能保证

例如,它不会在我当前运行的机器上停止——但同样,我可以在另一台机器上尝试完全相同的可执行文件,它可能运行良好。这将取决于运行它的 CLR 使用的确切内存模型语义。这将受到底层架构的影响,甚至可能会受到所使用的确切 CPU 的影响。

请务必注意,不是 C# 编译器 决定如何处理 volatile 字段 - C# 编译器仅使用 System.Runtime.CompilerServices.IsVolatile 指示元数据中的易变性。然后,JIT 可以计算出遵守相关契约(Contract)意味着什么。

关于C# 编译器优化和 volatile 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17907885/

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