简体   繁体   中英

How TPL works in a multicore processor

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();

How will this work in the core 2 duo processor. I am actually trying to get my concepts clear.

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.

  • If there's nothing there and it's in the main method, the task will probably stop in the middle.

  • 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM