并行库 MaxDegreeOfParallelism 值? [英] Parallel Library MaxDegreeOfParallelism value?

查看:28
本文介绍了并行库 MaxDegreeOfParallelism 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是线程和并行库的新手.我试图了解 MaxDegreeOfParallelism 以及它应该设置的值.

I am new to threading and parallel library. I am trying to understand the MaxDegreeOfParallelism and to what value it should be set.

读了一些书,对我来说可能有点误导.

Done some reading and to me might be a bit misleading.

如果我想在 4 个线程上运行,我认为我可以做到

If I want to run on 4 threads I thought I could do

var parOptions=new ParallelOptions();
parOptions.MaxDegreeOfParallelism=4;

然而,多读一些书,在我的情况下,4 并不意味着在 4 个线程上运行,而是更多地与核心及其使用量有关.

However doing some more reading it looks like that in my case 4 does not mean runs on 4 threads but is more todo with Cores and how much it uses.

为了简单起见,设置它应该运行的线程数的正确方法是什么?或者,也许您可​​以设置它可以使用的多个线程,但更多地设置它使用的内核数量

To keep it simple what is the correct way to set the number of threads it should run? Or maybe you can set on many threads it can use but more on how much cores it uses

我计划在 config.eg "ThreadCount" 中设置一个用户可以指定的值.这是其他开发人员将运行以导入内容的内部应用程序.

I am planning in having a settings in config.eg "ThreadCount" with a value that the user can specify. This is an internal application that other developers will run to import stuff.

对此有任何澄清吗?谢谢

any clarification on this? thanks

推荐答案

您似乎不了解调度线程的工作原理,您可能需要阅读相关内容.简而言之,程序可以创建线程,但它对线程运行的时间和内核几乎没有控制,这是操作系统的工作.

It seems like you don't understand how scheduling threads works, you might want to read up about it. In short, a program can create threads, but it has very little control about when and what core will a thread run on, that's the job of the operating system.

因此,当您的程序创建 4 个线程时,操作系统可能会(通常很有可能)决定在其 4 个内核上运行这 4 个线程.但是,如果有其他进程已经在使用 CPU,例如,操作系统可能会决定在单个内核上运行这 4 个线程.

So, when your program creates 4 threads, it's possible (and usually quite likely) that the OS will decide to run those 4 threads on its 4 cores. But if there are other processes already using the CPU, the OS might for example decide to run those 4 threads on a single core.

现在,如果您将 MaxDegreeOfParallelism 设置为 4,则意味着使用这些 ParallelOptionsParallel 循环最多可以使用 4 个线程来运行循环,但不能更多(尽管允许使用更少).如果它决定创建 4 个线程,那么这些线程将在最多 4 个内核上运行,这由操作系统决定.

Now, if you set MaxDegreeOfParallelism to 4, it means that the Parallel loop that uses these ParallelOptions may use up to 4 threads to run the loop, but not more (though it is allowed to use less). If it decides to create 4 threads, those will be run on up to 4 cores, which is decided by the OS.

但是当您的代码受 CPU 限制时(即您不读取文件或使用网络或类似的东西),通常最好不设置 MaxDegreeOfParallelism,TPL将尝试找到要使用的最佳线程数.

But when your code is CPU-bound (i.e. you're not reading files or using the network or something like that), then it's usually best if you don't set MaxDegreeOfParallelism, the TPL will try to find the optimal amount of threads to use.

这篇关于并行库 MaxDegreeOfParallelism 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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