【发布时间】:2017-11-15 13:44:00
【问题描述】:
我尝试了解 volatile 在多线程上下文中的使用。以下代码来自网上another source of knowledge:
class Program
{
static string _result;
//static volatile bool _done;
static bool _done;
static void SetVolatile()
{
// Set the string.
_result = "Dot Net Perls";
// The volatile field must be set at the end of this method.
_done = true;
}
static void Main()
{
// Run the above method on a new thread.
new Thread(new ThreadStart(SetVolatile)).Start();
// Wait a while.
Thread.Sleep(200);
// Read the volatile field.
if (_done)
{
Console.WriteLine(_result);
}
}
}
volatile 关键字的演示使用应该可以防止线程读取存储在缓存中的值。而不是这个,它应该检查一个实际值。
因此,如果没有 volatile 的 _done 应该仍然有一个 false 值(从缓存中读取)并且不应执行 Console.WriteLine 语句。
不幸的是,在没有 volatile 关键字的调试/发布模式下运行此代码总是会产生输出。这个特定示例的意义何在?
【问题讨论】:
-
如果没有
volatile,编译器(静态和 JIT)可能优化读取,使赋值永远不会被看到,如果你严格阅读标准。但它不是必需,事实上,我认为.NET(过去或现在)的任何 JIT 编译器实际上都不会这样做,至少不是这种特定情况,不是在 x86/x64 . -
如果你想了解这些东西,那么开始阅读一些serious stuff也许吧?
-
"在我们开始之前,请注意这个例子并不理想,因为它在没有 volatile 修饰符的情况下也能正常工作。它仅用于说明 volatile 关键字的概念,而不是提供一个真实的例子” - 来自internet。
-
请参阅this answer 以了解使用
volatile实际上确实会产生影响的示例。
标签: c# multithreading volatile