使用多核(线程)处理器进行 FOR 循环
Using Multi-core (-thread) processor for FOR loop
我有一个简单的循环用于:
for (int i = 1; i <= 8; i++)
{
DoSomething(i);
}
int nopt = 8; //number of processor threads
我想在处理器线程 1 中执行 DoSomething(1)
,
DoSomething(2)
在线程 2 中执行
...
DoSomething(8)
在线程 8 中。
可能吗?如果是,那么如何?
感谢您的回答。
你可以试试Parallel.For
:
int nopt = 8;
ParallelOptions po = new ParallelOptions() {
MaxDegreeOfParallelism = nopt,
};
// 9 is exclusive when you want i <= 8
Parallel.For(1, 9, po, i => DoSomething(i));
PLinq(并行 Linq)是一个备选方案:
Enumerable
.Range(1, 8)
.AsParallel()
.WithDegreeOfParallelism(nopt)
.ForAll(i => DoSomething(i));
我有一个简单的循环用于:
for (int i = 1; i <= 8; i++)
{
DoSomething(i);
}
int nopt = 8; //number of processor threads
我想在处理器线程 1 中执行 DoSomething(1)
,
DoSomething(2)
在线程 2 中执行
...
DoSomething(8)
在线程 8 中。
可能吗?如果是,那么如何?
感谢您的回答。
你可以试试Parallel.For
:
int nopt = 8;
ParallelOptions po = new ParallelOptions() {
MaxDegreeOfParallelism = nopt,
};
// 9 is exclusive when you want i <= 8
Parallel.For(1, 9, po, i => DoSomething(i));
PLinq(并行 Linq)是一个备选方案:
Enumerable
.Range(1, 8)
.AsParallel()
.WithDegreeOfParallelism(nopt)
.ForAll(i => DoSomething(i));