使用Parallel Extensions時是否需要關注MemoryBarriers?MemoryBarriers和並行擴展
編輯 - 擬定爲原來的問題是開放式的: (@xanatos的回答是一個我一直在尋找)
舉一個具體的例子:假設我使用Parallel.ForEach和每次迭代設置類中屬性的值(每次迭代設置它自己的特定屬性,沒有兩次迭代設置相同屬性的值)。在調用Parallel.ForEach的同一個線程上,我訪問從Parallel.ForEach設置的屬性。
class Program
{
static void Main(string[] args)
{
var t = new Test();
t.InitializePropertiesInParallel();
var a = t.PropA; // Could never be 0?
var b = t.PropB; // Could never be 0?
}
}
public class Test
{
public int PropA { get; set; }
public int PropB { get; set; }
public void InitializePropertiesInParallel()
{
var initializers = new List<Action<int>>()
{
i => PropA = i,
i => PropB = i
};
initializers.AsParallel().ForAll(a => a(1));
}
}
這取決於你在做什麼並行。 – SLaks 2012-03-13 17:10:08
請詳細說明。在目前的形式下,你的問題有點不確定。 – 2012-03-13 17:10:52
按要求精心佈置。 – dugas 2012-03-14 03:44:47