简体   繁体   中英

parallel programming in TPL

im using tasks parallel library in .net 4.0 i want to have the ability to specify a task for each core independant of the other cores. usually in TPL, i create a task and i tell it to run in parallel, i have no control over the number of threads created nor can i control the number of cores to participate in the parallel task. also, i cant specify each particular core a different task. i'd like to know how to achieve this in TPL if it is possible.

The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. If this is a problem, TPL may not be for you.

The closest thing I'm aware of is ParallelEnumerable.WithDegreesOfParallelism , which sets the the maximum number of concurrently executing tasks that will be used to process the query.

It doesn't sound like that fits your bill, however, so perhaps you need fine-grained control, in which case I'd recommend using threads directly.

i have no control over the number of threads created nor can i control the number of cores to participate in the parallel task.

By design, the purpose of the TPL is that you don't have to deal with those issues. Tuning can be very complicated, the TPL does a pretty good job.

As others have pointed out, you probably don't want to do this.

There is a ParallelExtensionsExtras library on CodePlex that has various task schedulers , one of which is a "thread per task" scheduler, and another ( LimitedConcurrencyLevelTaskScheduler ) that allows you to specify the degree of parallelism.

However, they don't provide thread affinity to a particular core. You'd have to code this on your own.

I just noticed that there is a way to control the degree of parallelism in TPL. Example code is as below, which uses ParallelOptions to decide the max concurrency in parallel execution of a loop.

This is taken from an article by Richard Carr at: Control Degree of Parallelism in TPL

ParallelOptions po = new ParallelOptions();
po.MaxDegreeOfParallelism = 2;

Parallel.For(0, 20, po, i =>
{
    Console.WriteLine("{0} on Task {1}", i, Task.CurrentId);
});

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