0

in my program the matrix is presented as an jagged array, using multithreading, I count the sum of all elements of a column, and I assign this sum to an element on the main diagonal. Do I need to use a lock(), if each thread works with a separate column?

int[][] matrix = new int[n][];// jagged array
for (int i = 0; i < n; i++)// run thread
  {

    int f = i;
    threads[i] = new Thread(new ThreadStart(() => 
     parallelSuma(matrix1,f,1)));
    threads[i].Start();
                
    }
private void parallelSuma(int[][] data, int f, int columnPerThread) {
        
        for (int i = f; i <f+columnPerThread; i++)
        {

            for (int j = 0; j < data.Length; j++)
            {

                if(i==j)
                    continue;
                data[i][i] += data[j][i];
            }
        }
    }
  • Well you shouldn't be using threads or custom [parallel infrastructure](https://dotnettutorials.net/lesson/parallel-for-method-csharp/#:~:text=In%20case%20of%20the%20standard%20C#%20for%20loop,,in%20the%20case%20of%20Parallel%20For%20loop), as for locks from what I can see this will throw an exception since you don't initialize the internal arrays and a lock would be necessary to do it. – Filip Cordas Feb 15 '21 at 17:09
  • Not counting the fact that jagged arrays require initialization not present in your example, in general as long as threads don't try to access the same array elements as other threads, it's fine. See duplicate. – Peter Duniho Feb 15 '21 at 18:08

0 Answers0