TPL 如何在多核处理器中工作 [英] How TPL works in a multicore processor

查看:82
本文介绍了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.ForPLINQ:

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.

这篇关于TPL 如何在多核处理器中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆