locked
Parallel.For loop question RRS feed

  • Question

  • Hello,

    I am new to "Parallel.For" loops. I have red that it is important to not write to shared variables as the indexes in the loop executes in different orders when cores are avaliable. (My system has 24 cores, 32GB RAM)

    As in example 1 with the for loop, as seen "str" is declared OUTSIDE the loop which is okay because it is processed inside the loop one index at a time.

    Question: Is it correct to declare the "str" INSIDE the "Parallel.For" loop as each iteration will have its own "str" where they can't be mixed with other indexes in the loop?

                        List<String> list1 = new List<String>();
                        String str = "";
                        for (int i = 0; i < list1.Count; i++)
                        {
                            str = i.ToString();
                        }
    
                        Parallel.For(0, list1.Count, i =>
                        {
                            String str = i.ToString(); 
                        });

    Friday, March 25, 2016 7:33 PM

Answers

  • "Is it correct to declare the "str" INSIDE the "Parallel.For" loop as each iteration will have its own "str" where they can't be mixed with other indexes in the loop?"

    Yes, it is correct. It's correct even for a non-parallel loop if the variable doesn't need to be used outside of the loop.

    • Marked as answer by Silvers2 Friday, March 25, 2016 9:29 PM
    Friday, March 25, 2016 8:00 PM

All replies

  • "Is it correct to declare the "str" INSIDE the "Parallel.For" loop as each iteration will have its own "str" where they can't be mixed with other indexes in the loop?"

    Yes, it is correct. It's correct even for a non-parallel loop if the variable doesn't need to be used outside of the loop.

    • Marked as answer by Silvers2 Friday, March 25, 2016 9:29 PM
    Friday, March 25, 2016 8:00 PM
  • Thank you, that cleared it out!

    Thanks

    Friday, March 25, 2016 9:28 PM