简体   繁体   English

为什么ThreadPool仅启动一个线程?

[英]Why ThreadPool start only one thread in time?

I start threads exactly like book says: 我完全按照书中所述启动线程:

for (int i = 1; i <= 4; i++) {
  ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadMethod), i);
}

ThreadMethod looks like: ThreadMethod看起来像:

static void ThreadMethod(object input) {
  Console.WriteLine(input + " thread started");
  //do some stuff for, like, 400 milliseconds
  Console.WriteLine(input + " thread completed");
}

In some reason 2 thread starts only after 1 is completed (in this moment all work is already done and 2-4 thread just start and stop doing nothing). 出于某种原因,只有2个线程在1个线程完成后才启动(此时所有工作已经完成,而2-4个线程只是启动和停止执行任何操作)。

What could be wrong? 有什么事吗 Ask anything what could help solve this problem. 询问任何可以帮助解决此问题的方法。 I don't use any synchronization classes. 我不使用任何同步类。

If it's matter, i have 2 core processor. 如果有关系,我有2核心处理器。

Your ThreadMethod just runs too fast. 您的ThreadMethod运行得太快了。 Everything is right with your code except if possible you should switch from ThreadPool to new abstractions like Task.Run . 一切都对您的代码是正确的,除非可能,您应该从ThreadPool切换到Task.Run类的新抽象。

Actually, as i made ThreadMethod to do much longer stuff, another threads started after some time but it don't worked in one time but just switches from thread to thread. 实际上,当我使ThreadMethod可以做更长的工作时,一段时间后又启动了另一个线程,但是一次也没有用,只是在一个线程之间切换。 Looks like i have to use another tool. 看来我必须使用其他工具。

A TreadPool has a maximum number of threads that it can use. TreadPool具有可以使用的最大线程数。 See ThreadPool.GetMaxThread and SetMaxThread. 请参见ThreadPool.GetMaxThread和SetMaxThread。 It is probably equal to the number of available cores by default. 默认情况下,它可能等于可用核心数。

For CPU intensive work it makes sense since you would actually lower performance by using more threads than you have cores. 对于CPU密集型工作,这是有道理的,因为实际上使用多于​​内核的线程会降低性能。 However, for slow jobs such as I/O intensive jobs, many threads can run in parallel to avoid blocking and wait until the I/O is complete. 但是,对于诸如I / O密集型作业之类的较慢的作业,许多线程可以并行运行以避免阻塞,并等到I / O完成。 Example: Grabing several files at a time from various FTP servers. 示例:一次从多个FTP服务器获取多个文件。

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

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