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