3

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

svick
  • 236,525
  • 50
  • 385
  • 514

1 Answers1

8

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.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • lock (lockobject){b1.Add(i);} should fix it?. Of course as you said, it defeats the point of a parallel for. – NoviceProgrammer Dec 29 '12 at 06:19
  • 1
    @NoviceProgrammer yes, but as mike mentioned, in this particular example, locking before adding defeats the purpose of multiple threads: you are still only adding one element at a time to the list. – vlad Dec 29 '12 at 06:21
  • @NoviceProgrammer yes that is a typical way to synchronize and it is perfectly fine if more substantial work is being done by each thread so that there is little contention for the lock. – Mike Zboray Dec 29 '12 at 06:25
  • and does the newer types like ConcurrentBag do the same thing underneath? – NoviceProgrammer Dec 29 '12 at 06:26
  • did a quick check and using ConcurrentBag in this rather unrealistic example was a quite a bit slower than using the lock – NoviceProgrammer Dec 29 '12 at 06:26
  • @NoviceProgrammer Interesting. I believe `ConcurrentBag` and the other classes in that namespace are lock-free. – Mike Zboray Dec 29 '12 at 06:29