2

I have the following code:

string someVariable;

Parallel.For(0, maxCount, count =>
{
    Parallel.For(0, dimension, row =>
    {
        Parallel.For(0, dimension, col =>
        {
            someVariable = count + " " + row + " " + col;
            DoSomethingIndependent(someVariable);
        });
    });
});

So my question is: is the string variable which is declared outside the loops is independent from each iteration or does the parallel execution of the loops is interrupting with the iterations between each other? I guess that the variable is used at the same time from to parallel threads because it gives me an "Unhandled exception". What is the best way to do this? Maybe using an array of strings for each parallel iteration?
Thanks in advance!

  • 2
    Do you need `someVariable` afterwards? Otherwise you should declare it in the inner loop (`var someVariable = count ...`). – CodeCaster Dec 07 '12 at 13:26
  • @CodeCaster - Nope, I don't need it afterwards. Will this declaration slow down significantly the execution of the code? Well, I guess that it's better than declaring an array. I hadn't thought of making it this way, thanks for the suggestion. I will try it. – Simeon Nikolov Dec 07 '12 at 13:37
  • @performance: see [Does moving variable declaration outside of a loop actually increase performance?](http://stackoverflow.com/questions/6343644/does-moving-variable-declaration-outside-of-a-loop-actually-increase-performance). – CodeCaster Dec 07 '12 at 13:38
  • Thank you, now it works fine and I'm glad that there is no performance difference. – Simeon Nikolov Dec 07 '12 at 13:42

1 Answers1

1

There are a number of things wrong with the code in your question.

1) Nobody mentioned this in the comments above but someVariable is being written to by multiple threads. This will cause correctness issues. You have to declare someVariable within the inner loop so that each task has it's own instance of someVariable to update.

2) Where a variable is declared has minimal impact on performance. This is not the same as the link above which refers to sequential loops. Here the compiler is not able to move veriable instantiations in or out of the parallel loop but the overhead of instantiating a variable should be minimal assuming your loop is doing any significant amount of work. If DoSomethingIndependent is not doing real work then parallelizing it is unlikely to give a performance benefit anyways.

3) Using three parallel for each loops nested like this is unlikely to be very efficient. You'd be better off just having a parallel for each on the outer loop and just use sequential loops for the inner two.

4) Assuming rows and cols refers to some data stored in a 2D array somewhere then you should reverse the order of the two inner loops. Remember that arrays are stored in row-major order.

Ade Miller
  • 13,575
  • 1
  • 42
  • 75