C # Parallel.For creating an array: OK to put lock () in an array?

I have a C # static static method to create an array ( double : s) and therefore parallelized the operation.

Since I create an array before entering the loop, and then not changing it with a link after that, I think that it should be sufficient to lock the array itself when it is updated in a parallel loop.

Is it possible to use lock in the array itself, or can I encounter some performance or deadlock problems with this approach? Is it better to create a separate lock variable to enable locking?

Here is an example 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; } 
+4
source share
1 answer

Since array is a reference type here, it is not reassigned during operations and is not yet displayed elsewhere (where some other code could block it), yes, it can be enough as the lock object itself. However, if the updates relate to different parts of the array, i.e.

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

then there is no need to block anything.

+9
source

All Articles