假设我有一个4核CPU,我想在最短的时间内运行某个进程。这个过程在理想情况下是可并行的,所以我可以在无数个线程上运行它的块,每个线程花费相同的时间。

因为我有4个内核,所以我不期望通过运行比内核更多的线程来提高速度,因为单个内核在给定时刻只能运行单个线程。我对硬件了解不多,所以这只是一个猜测。

在更多的线程而不是核心上运行并行进程是否有好处?换句话说,如果我使用4000个线程而不是4个线程运行,我的进程会更快、更慢,还是在大约相同的时间内完成?


当前回答

大量线程(“线程池”)vs每个核心一个线程的一个例子是在Linux或Windows中实现web服务器。

由于在Linux中套接字是轮询的,因此许多线程可能会增加其中一个线程在正确的时间轮询正确的套接字的可能性——但总体处理成本将非常高。

在Windows中,服务器将使用I/O完成端口(IOCPs)实现,这将使应用程序事件驱动:如果I/O完成,操作系统将启动一个备用线程来处理它。当处理完成时(通常是请求-响应对中的另一个I/O操作),线程返回IOCP端口(队列)等待下一次完成。

如果没有I/O完成,就没有要做的处理,也没有启动线程。

事实上,微软建议在IOCP实现中每个核不超过一个线程。任何I/O都可以附加到IOCP机制。如果需要,应用程序也可以发布IOCs。

其他回答

一次4000个线程是相当高的。

答案是肯定的,也不是。如果您在每个线程中执行大量阻塞I/O,那么是的,您可以在每个逻辑核心中执行3或4个线程时显示显著的加速。

If you are not doing a lot of blocking things however, then the extra overhead with threading will just make it slower. So use a profiler and see where the bottlenecks are in each possibly parallel piece. If you are doing heavy computations, then more than 1 thread per CPU won't help. If you are doing a lot of memory transfer, it won't help either. If you are doing a lot of I/O though such as for disk access or internet access, then yes multiple threads will help up to a certain extent, or at the least make the application more responsive.

如果你的线程不做I/O,同步等,没有其他的运行,1个线程一个核可以让你获得最好的性能。然而,情况很可能并非如此。添加更多的线程通常会有所帮助,但在某种程度上,它们会导致性能下降。

Not long ago, I was doing performance testing on a 2 quad-core machine running an ASP.NET application on Mono under a pretty decent load. We played with the minimum and maximum number of threads and in the end we found out that for that particular application in that particular configuration the best throughput was somewhere between 36 and 40 threads. Anything outside those boundaries performed worse. Lesson learned? If I were you, I would test with different number of threads until you find the right number for your application.

有一件事是肯定的:4k线程将花费更长的时间。这有很多上下文转换。

基准。

我会开始增加应用程序的线程数,从1开始,然后增加到100,对每个线程数运行3 - 5次试验,并建立一个操作速度与线程数的关系图。

您应该认为四个线程的情况是最优的,在此之后运行时略有增加,但也可能不是。这可能是你的应用程序带宽有限,也就是说,你加载到内存中的数据集是巨大的,你得到了很多缓存失误,等等,这样2个线程是最佳的。

你不测试就不知道。

实际性能取决于每个线程的自愿屈服程度。例如,如果线程根本不做I/O,也不使用任何系统服务(即它们100%受cpu限制),那么每个核1个线程是最优的。如果线程执行任何需要等待的操作,那么您必须试验以确定最佳线程数。4000个线程会导致大量的调度开销,所以这可能也不是最优的。

理想的情况是每个内核有一个线程,只要没有线程会阻塞。

在一种情况下,这可能是不正确的:有其他线程在核心上运行,在这种情况下,更多的线程可能会给您的程序更大的执行时间。