并行处理中的值存储 [英] Value storage during Parallel Processing
问题描述
我只是试用了这个简单的程序……没什么花哨的..
I just tried out this simple program... nothing fancy..
double[] a = new double[100000];
double[] b = new double[100000];
List<double> a1 = new List<double>();
List<double> b1 = new List<double>();
for (Int64 i = 0; i < 100000; i++)
{
a[i] = i;
a1.Add(i);
}
Parallel.For(0, 100000, delegate(Int64 i)
{
b[i] = i;
b1.Add(i);
});
根据此代码,必须分别在a,b,a1,b1中存储100000个数字.但是有时,变量b1(由并行处理更新的列表)的数字少于100000(保持在90000到100000之间).我不知道为什么...
According to this code, 100000 numbers must be stored in a, b, a1, b1 each. But at times, the variable b1 (List updated by the Parallel Process) has less than 100000 numbers (Keeps varying between 90000 and 100000). I wonder why...
推荐答案
List<T>
is not thread-safe for multiple threads to be writing simultaneously, as described on the MSDN page. You must synchronize access (defeating the purpose of multiple threads) or use a thread-safe collection. There are thread-safe collections available in the System.Collections.Concurrent
namespace.
这篇关于并行处理中的值存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!