什么时候应该使用线程? [英] When Should I Use Threads?

查看:118
本文介绍了什么时候应该使用线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,理想的线程数量是3:一个用于UI,一个用于CPU资源,一个用于IO资源.

As far as I'm concerned, the ideal amount of threads is 3: one for the UI, one for CPU resources, and one for IO resources.

但是我可能错了.

我刚刚被介绍给他们,但是我一直在UI中使用一个,而在其他所有方面都使用一个.

I'm just getting introduced to them, but I've always used one for the UI and one for everything else.

我什么时候应该使用线程以及如何使用线程?我怎么知道我是否应该使用它们?

When should I use threads and how? How do I know if I should be using them?

推荐答案

不幸的是,使用线程没有硬性规定.如果线程太多,则处理器将花费所有时间来生成线程并在它们之间进行切换.使用的线程太少,您将无法在应用程序中获得所需的吞吐量.另外,使用线程并不容易.像C#这样的语言使您更轻松,因为您拥有像ThreadPool.QueueUserWorkItem这样的工具.这使系统可以管理线程的创建和销毁.这有助于减轻创建新线程以将工作传递到的开销.您必须记住,创建线程不是您免费"获得的操作.启动线程存在成本,因此应始终将其考虑在内.

Unfortunately, there are no hard and fast rules to using Threads. If you have too many threads the processor will spend all its time generating and switching between them. Use too few threads you will not get the throughput you want in your application. Additionally using threads is not easy. A language like C# makes it easier on you because you have tools like ThreadPool.QueueUserWorkItem. This allows the system to manage thread creation and destruction. This helps mitigate the overhead of creating a new thread to pass the work onto. You have to remember that the creation of a thread is not an operation that you get for "free." There are costs associated with starting a thread so that should always be taken into consideration.

根据您用来编写应用程序的语言,您将确定需要担心使用线程的程度.

Depending upon the language you are using to write your application you will dictate how much you need to worry about using threads.

我发现最需要考虑显式创建线程的时间是:

The times I find most often that I need to consider creating threads explicitly are:

  • 异步操作
  • 可以并行化的操作
  • 连续运行的后台操作

这篇关于什么时候应该使用线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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