并行处理中的值存储 [英] Value storage during Parallel Processing

查看:45
本文介绍了并行处理中的值存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试用了这个简单的程序……没什么花哨的..

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>对于多个线程同时写入来说不是线程安全的,如

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆