Search code examples
c#parallel.foreach

Parallel For c#


I'm trying to improve the performance of a method that calculates the mean of an image.

For that I'm using two For statements to iterate all the image, therefore I tried to use a Parallel For to improve this, but the results are not the same.

Am I doing it wrong? or what is it causing the difference?

public static double MeanDN(this GrayImage image)
{
  double mean = 0;
  int totalPixels = image.Width * image.Height;

  for (int i = 0; i < image.Height; i++)
      for (int j = 0; j < image.Width; j++)
          mean += (double)image[i, j] / totalPixels;

  double parallelMean = 0;

  Parallel.For(0, image.Height, i =>
  {
      for (int j = 0; j < image.Width; j++)
          parallelMean += (double)image[i, j] / totalPixels;
  });

  return mean;
}

Output:

mean = 404.12

parallelMean = 148.8658


Solution

  • Your Problem is that you let multiple tasks modify the same variable parallelMean. So you have a Race Condition.
    I think also that the second result is not only false, it is also not stable: Mean try to execute the code again, and the second result will change
    I think this code could solve your problem

    double[] parallelMean = new double[image.Height];
    
    Parallel.For(0, image.Height, i =>
    {
        for (int j = 0; j < image.Width; j++)
            parallelMean[i] += (double)image[i, j] / totalPixels;
    });
    
    return parallelMean.Sum();