线程与线程池 [英] Thread vs ThreadPool

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

问题描述

使用新线程和使用线程池中的线程有什么区别?有什么性能优势,为什么我应该考虑使用池中的线程而不是我明确创建的线程?我在这里专门考虑 .NET,但一般示例都很好.

What is the difference between using a new thread and using a thread from the thread pool? What performance benefits are there and why should I consider using a thread from the pool rather than one I've explicitly created? I'm thinking specifically of .NET here, but general examples are fine.

推荐答案

线程池将为频繁且相对较短的操作提供好处

Thread pool will provide benefits for frequent and relatively short operations by

  • 重用已经创建的线程而不是创建新线程(一个昂贵的过程)
  • 当对新工作项的请求激增时限制线程创建的速度(我相信这仅在 .NET 3.5 中)
    • 如果您将 100 个线程池任务排入队列,它只会使用已创建的线程数来为这些请求提供服务(例如 10 个).线程池会进行频繁的检查(我相信在 3.5 SP1 中每 500 毫秒一次),如果有排队的任务,它将创建一个新线程.如果您的任务很快,那么新线程的数量将会很少,并且将 10 个左右的线程重用于短任务比预先创建 100 个线程要快.

    • Reusing threads that have already been created instead of creating new ones (an expensive process)
    • Throttling the rate of thread creation when there is a burst of requests for new work items (I believe this is only in .NET 3.5)
      • If you queue 100 thread pool tasks, it will only use as many threads as have already been created to service these requests (say 10 for example). The thread pool will make frequent checks (I believe every 500ms in 3.5 SP1) and if there are queued tasks, it will make one new thread. If your tasks are quick, then the number of new threads will be small and reusing the 10 or so threads for the short tasks will be faster than creating 100 threads up front.

      如果您的工作负载始终有大量线程池请求进入,那么线程池将通过上述过程在池中创建更多线程来调整自己以适应您的工作负载,以便有更多线程可用于处理请求

      If your workload consistently has large numbers of thread pool requests coming in, then the thread pool will tune itself to your workload by creating more threads in the pool by the above process so that there are a larger number of threads available to process requests

      检查 此处 了解有关线程池如何在后台运行的更深入信息

      check Here for more in depth info on how the thread pool functions under the hood

      如果作业的运行时间相对较长(可能大约一两秒钟,但这取决于具体情况),自己创建一个新线程会更合适.

      Creating a new thread yourself would be more appropriate if the job were going to be relatively long running (probably around a second or two, but it depends on the specific situation)

      @Krzysztof - 线程池线程是后台线程,会在主线程结束时停止.手动创建的线程默认为前台(在主线程结束后会继续运行),但可以在调用 Start 之前将其设置为后台.

      @Krzysztof - Thread Pool threads are background threads that will stop when the main thread ends. Manually created threads are foreground by default (will keep running after the main thread has ended), but can be set to background before calling Start on them.

      这篇关于线程与线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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