Parallel.For使用步骤!= 1 [英] Parallel.For using step != 1
问题描述
有没有办法为循环实现这个的
Parallel.For
版本? (int i = 0; i <100; i + = 2){DoStuff(i); }
我没有看到接受step参数的重载,但我想不出任何理由这在逻辑上是不可能的。
这和这个 a>问题建议在使用 Enumerable生成的
范围内使用 Parallel.ForEach
范围,但在我的情况下,我使用线程本地数据所以。 Parallel.ForEach
不是一个选项
另一种方法是检查我的循环体内是否存在 i%2 == 0
, return
,但仍然执行线程本地数据intializer Func
和终结器 Func
。下面是显示这个选项的代码片段:
Parallel.For< Bar>(0,limit,
()=> new Bar(),//线程本地数据初始化
(i,state,local)=> //循环体
{
if (i%2!= 0)return local;
local.foo + = DoStuff(i);
return local;
},
(local)= > //线程本地数据后处理
{
lock(loopLocker)
{
globalData.foo + = local.foo;
);
}
);
这里有个提示:对于(int j = 0; j <50; j ++){i = 2 * j; b ++),b
做东西();一般来说,看看你是否可以计算出迭代次数和从迭代次数到变换次数的变换变量值。
Is there any way to achieve the Parallel.For
version of this for
loop?
for (int i = 0; i < 100; i += 2) { DoStuff(i); }
I don't see an overload which accepts a step parameter, though I can't think of any reason this would be logically impossible.
The accepted answer to this and this question suggests using Parallel.ForEach
on a range of int
s generated using Enumerable.Range
, but in my case I am using thread local data so Parallel.ForEach
is not an option.
Another option is to just check if i % 2 == 0
in the body of my loop and return
, but this still executes the thread local data intializer Func
and finalizer Func
. Below is a code snippet demonstrating this option:
Parallel.For<Bar>(0, limit,
() => new Bar(), //thread local data initialize
(i, state, local) => //loop body
{
if (i % 2 != 0) return local;
local.foo += DoStuff(i);
return local;
},
(local) => //thread local data post-action
{
lock (loopLocker)
{
globalData.foo += local.foo;
);
}
);
解决方案 Here's a hint:
for (int j = 0; j < 50; j++) { i = 2*j; DoStuff(); }
In general, see if you can figure out the number of iterations and a transformation from iteration number to the variable value.
这篇关于Parallel.For使用步骤!= 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!