TPL 如何在多核处理器中工作
我是 C# 4.0 并行编程的新手.我知道并行编程和多线程是两个不同的东西.如果我创建如下任务,现在在 TPL 中:
I am new to parallel programming in C# 4.0. I understand that Parallel Programming and Multithreading are two different things. Now in TPL if I create a task like below:
Task<int> task1 = new Task<int>(() => {
for (int i = 0; i < 100; i++) {
sum += DoSomeHeavyCalculation(i);
}
return sum;
});
// start the task
task1.Start();
这将如何在 core 2 duo 处理器中工作.我实际上是想弄清楚我的概念.
How will this work in the core 2 duo processor. I am actually trying to get my concepts clear.
task1
的计算将在单线程上执行,与您当前所在的线程不同*.实际发生的情况取决于您发布的代码下方的代码.
The calculation for task1
will be executed on single thread, different* from the one you're currently on. What actually happens depends on the code below the one you posted.
如果那里什么都没有,并且在 main 方法中,那么任务可能会在中间停止.
If there's nothing there and it's in the main method, the task will probably stop in the middle.
如果有task1.Wait()
或者使用task1.Result
的东西,当前线程会一直等到任务完成,你不会得到使用 TPL 的任何性能优势.
If there's task1.Wait()
or something using task1.Result
, the current thread will wait until the task is finished and you won't get any performance benefits from using TPL.
如果还有一些其他繁重的计算,然后是上一点的一些东西,这两个计算将并行运行.
If there's some other heavy calculation and then something from the previous point, those two computations will run in parallel.
如果要使用所有可用内核并行运行 for
循环,则应使用 Parallel.For
或 PLINQ:
If you want to run a for
loop in parallel, using all your available cores, you should use Parallel.For
or PLINQ:
ParallelEnumerable.Range(0, 100).Select(DoSomeHeavyCalculation).Sum()
* 实际上,在某些情况下,任务可以在同一个实际线程上运行,但这与此处无关.
* In fact, the task can run on the same actual thread, under some circumstances, but that's not relevant here.