Parallel.ForEach 是否限制活动线程的数量? [英] Does Parallel.ForEach limit the number of active threads?

查看:20
本文介绍了Parallel.ForEach 是否限制活动线程的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

var arrayStrings = new string[1000];
Parallel.ForEach<string>(arrayStrings, someString =>
{
    DoSomething(someString);
});

所有 1000 个线程会几乎同时产生吗?

Will all 1000 threads spawn almost simultaneously?

推荐答案

不,它不会启动 1000 个线程 - 是的,它会限制使用的线程数.Parallel Extensions 使用适当数量的内核,具体取决于您实际拥有的内核数量 以及已经忙碌的内核数量.它为每个内核分配工作,然后使用一种称为工作窃取的技术,让每个线程高效地处理自己的队列,并且只在真正需要时才进行任何昂贵的跨线程访问.

No, it won't start 1000 threads - yes, it will limit how many threads are used. Parallel Extensions uses an appropriate number of cores, based on how many you physically have and how many are already busy. It allocates work for each core and then uses a technique called work stealing to let each thread process its own queue efficiently and only need to do any expensive cross-thread access when it really needs to.

查看PFX 团队博客加载的信息关于它如何分配工作和各种其他主题.

Have a look at the PFX Team Blog for loads of information about how it allocates work and all kinds of other topics.

请注意,在某些情况下,您也可以指定所需的并行度.

Note that in some cases you can specify the degree of parallelism you want, too.

这篇关于Parallel.ForEach 是否限制活动线程的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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