Eyad Alama
Eyad Alama

Reputation: 199

Variables inside a Parallel.For

So I have 3 nested for loops with the inner two doing little work. I want to convert the outer-most loop into a parallel one.

My question is:

If I have a variable inside the loop, something that is used as a temp value holder and takes a new value each loop. Do I need to worry about that variable when the parallelism begins ?

I mean are all the threads gonna be over-writing the same variable ?

 for (int i = 0; i < persons.number; i++) //Loop all the people
    var Dates = persons[i].Appointments.bydate(DateStep);

Do I need to worry about the Dates variable in the parallel loop ?

Sorry for the bad formatting of my question but it's only my second question and I'm getting there.

Upvotes: 4

Views: 1891

Answers (2)

Tudor
Tudor

Reputation: 62479

Dates will be local to each loop iteration, so each thread will have a private copy on its own stack. No interference.

Be careful about variables declared outside the loop though.

Upvotes: 3

Rotem
Rotem

Reputation: 21947

In short: No.

Because this variable is scoped inside the loop, it will be reassigned for every iteration of the loop anyways. It is not a value which is shared among different threads.

The only variables which you should worry about are those scoped outside of the loop.

Upvotes: 8

Related Questions