简体   繁体   English

Parallel.For中的变量

[英]Variables inside a Parallel.For

So I have 3 nested for loops with the inner two doing little work. 因此,我有3个嵌套的for循环,而内部的2个则很少工作。 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 ? 我是否需要担心并行循环中的Dates变量?

Sorry for the bad formatting of my question but it's only my second question and I'm getting there. 抱歉,我的问题格式不好,但这只是我的第二个问题,我已经到了。

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. 您唯一需要担心的变量是循环之外的变量。

Dates will be local to each loop iteration, so each thread will have a private copy on its own stack. Dates对于每个循环迭代都是本地的,因此每个线程在其自己的堆栈上都有一个私有副本。 No interference. 无干扰。

Be careful about variables declared outside the loop though. 但是要注意在循环外部声明的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM