Anders Gustafsson
Anders Gustafsson

Reputation: 15981

C# Parallel.For to create array: OK to put lock() on the array?

I have a time-consuming static C# method for creating an array (of double:s) and have therefore parallelized the operation.

Since I am creating the array before entering the loop and not tampering with its reference after that, I am thinking that it should be sufficient to lock the array itself while updating it within the parallel loop.

Is it OK to lock on the array itself or would I potentially face some performance or deadlock problems with this approach? Is it better to create a separate lock variable to put the lock on?

Here is some sample code to illustrate:

static double[] CreateArray(int mn, int n)
{
  var localLock = new object();    // Necessary?
  var array = new double[mn];

  Parallel.For(0, n, i =>
  {
    ... lengthy operation ...

    lock (array)    // or is 'lock (localLock)' required?
    {
      UpdatePartOfArray(array);
    }
  });

  return array;
}

Upvotes: 4

Views: 3011

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1064214

Since the array here is a reference type, isn't reassigned during the operations, and isn't exposed elsewhere yet (where some other code could lock it), yes, it can suffice as the lock object itself. However, if the updates are to different parts of the array, i.e.

array[i] = ... // i is separate

then there is no need to lock anything.

Upvotes: 10

Related Questions