Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});

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...

Strange Memory Allocation

like image 416
Sandeep Shankar Avatar asked Sep 22 '26 15:09

Sandeep Shankar


1 Answers

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.

like image 98
Mike Zboray Avatar answered Sep 25 '26 07:09

Mike Zboray