使用多核(-thread)处理器进行FOR循环

时间:2016-12-05 10:01:28

标签: c# multithreading multicore

我有一个简单的循环:

for (int i = 1; i <= 8; i++)
{
    DoSomething(i);
}
int nopt = 8; //number of processor threads

我想在处理器主题1中执行DoSomething(1),在主题2中执行DoSomething(2),在主题8中执行{
1}}。DoSomething(8)

有可能吗?如果是,那么?

感谢您的回答。

1 个答案:

答案 0 :(得分:11)

您可以尝试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 (Parallel Linq)是另一种选择:

  Enumerable
    .Range(1, 8)
    .AsParallel()
    .WithDegreeOfParallelism(nopt)
    .ForAll(i => DoSomething(i));