For nested in parallel

Asked

Viewed 140 times

1

I’m trying to spin two for nested. The second would like it to be parallel. It follows my code.

for (int i = 0; i < original.Width; i++)
    {
        Parallel.For(0, original.Height, j =>
        {
            Color originalColor = original.GetPixel(i, j);
            Color CorEmNegativo = Color.FromArgb(255 - originalColor.R, 255 - originalColor.G, 255 - originalColor.B);
            alterado.SetPixel(i, j, CorEmNegativo);
            Thread.Sleep(100);
        });
    }

The following error is returning to me: O objeto está sendo usado em outro lugar. How can I do ?

  • Which is the line of error?

  • I don’t think that’s gonna happen... The error is already saying, the (original) object is already being used in another process, as you are running the for in parallel, more than one thread is accessing the same object simultaneously, apparently there is a protection against it.

  • Probably the problem should be with the variable changed. You can try using this: lock(alterado) { alterado.SetPixel(i, j, CorEmNegativo); }

  • Same @Ricardopunctual error occurred

  • http://answall.com/a/169116/101

  • But it was wrong on which line???

  • On the line of Parallel.For ...

  • yesterday I took this test of him there using Task inside a normal For, gave the same error message, when trying to execute "original.Getpixel(i, j);"

Show 3 more comments

1 answer

1


I had to do it this way, and it worked:

for (int i = 0; i < original.Width; i++)
{
    Parallel.For(0, original.Height, j =>
     {
        lock (alterado)
        {
             Color originalColor = original.GetPixel(i, j);
             Color CorEmNegativo = Color.FromArgb(255 - originalColor.R, 255 - originalColor.G, 255 - originalColor.B);
             alterado.SetPixel(i, j, CorEmNegativo);
        }
    });
}
  • And it got faster?

  • No. That lock left twice the time practically

  • That’s what I figured. That’s what I’m talking about here: http://answall.com/q/1946/101

  • The lock you have implemented to solve the problem only makes it difficult to implement two nested not parallel, because for each cycle of the internal (theoretically parallel) is that the external is blocked by the lock. So the practical result is exactly the same (if not slower) as the conventional nested.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.