简体   繁体   English

TPL中的并行编程

[英]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. 我在.net 4.0中使用任务并行库,我希望能够为每个核心指定一个独立于其他核心的任务。 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. 通常在TPL中,我创建一个任务并告诉它并行运行,我无法控制创建的线程数,也无法控制参与并行任务的内核数。 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. 我想知道如何在TPL中实现这一目标。

The TPL scales the degree of concurrency dynamically to most efficiently use all the processors that are available. TPL动态缩放并发程度,以最有效地使用所有可用的处理器。 If this is a problem, TPL may not be for you. 如果这是一个问题,TPL可能不适合您。

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. 我所知道的最接近的东西是ParallelEnumerable.WithDegreesOfParallelism ,它设置将用于处理查询的并发执行任务的最大数量。

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. 调整可能非常复杂,TPL表现出色。

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. CodePlex上有一个ParallelExtensionsExtras库,其中包含各种任务计划程序 ,其中一个是“每个任务线程”计划程序,另一个( LimitedConcurrencyLevelTaskScheduler )允许您指定并行度。

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. 我刚刚注意到,有一种方法可以控制TPL中的并行度。 Example code is as below, which uses ParallelOptions to decide the max concurrency in parallel execution of a loop. 示例代码如下,它使用ParallelOptions决定并行执行循环的最大并发性。

This is taken from an article by Richard Carr at: Control Degree of Parallelism in TPL 这摘自Richard Carr的文章: TPL中的并行度控制

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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