Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 750
Anders Gustafsson Avatar asked Jan 17 '23 09:01

Anders Gustafsson


1 Answers

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.

like image 52
Marc Gravell Avatar answered Jan 30 '23 06:01

Marc Gravell