Parallel Foreach Loop - Odd Behavior

In the code below, you simply create a list> of random numbers, and then calculate the total of each list in a parallel foreach loop. Why am I getting less 'numLists' ratings? Often around 9990. I guess this has something to do with thread safety. What is an alternative method? (I am starting C #, so I hope I use the right conditions) Thank you.

using System; using System.Collections.Generic; using System.Threading.Tasks; namespace testParallelForeach { class Program { static void Main(string[] args) { List<List<double>> bsData = new List<List<double>>(); List<List<double>> cumsumDataP = new List<List<double>>(); int numLists = 10000; int myLen = 400; Random rand = new Random(); for (int i = 0; i < numLists; i++) { bsData.Add(new List<double>()); for (int j = 0; j < myLen; j++) { bsData[i].Add(rand.NextDouble()); } } Parallel.ForEach(bsData, a => cumsumDataP.Add(CumulativeSumParallel(a))); Console.WriteLine("cumsumDataP.Count={0}", cumsumDataP.Count); Console.ReadKey(); } public static List<double> CumulativeSumParallel(List<double> singleRetSeries) { int r = singleRetSeries.Count; List<double> cumsumList = new List<double>(); cumsumList.Add(singleRetSeries[0]); for (int i = 1; i < r; i++) { cumsumList.Add(cumsumList[i - 1] + singleRetSeries[i]); } return cumsumList; } } } 
+9
c # parallel-processing
Jan 24 '11 at 6:16
source share
1 answer

List<T> really not thread safe, so cumsupDataP.Add(...) displays data in unpredictable ways.

Replace this line as follows:

 ConcurrentBag<List<double>> cumsumDataP = new ConcurrentBag<List<double>>(); 

and everything will work. Note that the ConcurrentBag<T> unordered, but this is normal because you have no way to predict the order from the threads anyway; p

+11
Jan 24 '11 at 6:25
source share



All Articles