在下面的代码中,我填充字典的内容然后将其分配给
Data
。因此,我的心理预期是 Data
将包含 null
或包含两个元素的 Dictionary
。
但是这是一个有效的期望吗?
我知道写入可以被重新排序。据推测,简单的修复方法是将
volatile
添加到 Data
。但这有必要吗?或者原始代码保证“安全”(安全是指我可以 100% 确信 Data
永远不会包含具有 < 2 elements in it). 的字典)
using System;
using System.Collections.Generic;
public class Program
{
public static Dictionary<int, int> Data = null;
public static void Main()
{
var bob = new Dictionary<int, int>();
bob.Add(1, 1);
bob.Add(2, 2);
Data = bob;
// Note that there be no further mutation of `bob` or `Data` after this.
// Imagine there is a separate thread reading the contents of `Data`
}
}
我知道写入可以重新排序。据推测,简单的修复方法是将
添加到volatile
。但这有必要吗?Data
是的,绝对需要。如果没有
volatile
,编译器/抖动/处理器可能会 重新排序 程序的指令,使得 Data
可能会在短时间内指向部分初始化的 Dictionary<K,V>
对象。部分初始化的对象的行为是未定义的。它可能包含少于 2 个元素,它可能会抛出异常,等等。或者它可能会正常工作,因为实际上没有发生重新排序。如果你想负责任,不留一丝侥幸,你一定要把Data
声明为volatile
,这样就可以防止任何重新排序的可能性。