在C#.NET ConcurrentDictionary(C# reference source)的參考源代碼,我不明白爲什麼在下面的代碼片段需要性讀:C#揮發性讀行爲
public bool TryGetValue(TKey key, out TValue value)
{
if (key == null) throw new ArgumentNullException("key");
int bucketNo, lockNoUnused;
// We must capture the m_buckets field in a local variable.
It is set to a new table on each table resize.
Tables tables = m_tables;
IEqualityComparer<TKey> comparer = tables.m_comparer;
GetBucketAndLockNo(comparer.GetHashCode(key),
out bucketNo,
out lockNoUnused,
tables.m_buckets.Length,
tables.m_locks.Length);
// We can get away w/out a lock here.
// The Volatile.Read ensures that the load of the fields of 'n'
//doesn't move before the load from buckets[i].
Node n = Volatile.Read<Node>(ref tables.m_buckets[bucketNo]);
while (n != null)
{
if (comparer.Equals(n.m_key, key))
{
value = n.m_value;
return true;
}
n = n.m_next;
}
value = default(TValue);
return false;
}
註釋:
// We can get away w/out a lock here.
// The Volatile.Read ensures that the load of the fields of 'n'
//doesn't move before the load from buckets[i].
Node n = Volatile.Read<Node>(ref tables.m_buckets[bucketNo]);
混淆了我一點點。
在從數組中讀取變量n本身之前,CPU如何讀取n的字段?
我建議這是從[其他地方](http://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs,787)的複製和粘貼,因爲變量名不會在第二個例子中,當它們在這裏精確匹配時。儘管如此,我並沒有更接近辨別評論背後的意義。 –
http://www.catb.org/jargon/html/Y/You-are-not-expected-to-understand-this.html您必須瞭解弱內存模型的處理器是如何工作的。他們在市場上表現不佳,只有ARM內核今天真的很重要。體面的博客文章[在這裏](http://preshing.com/20120930/weak-vs-strong-memory-models/)。 –