When Should I Use Threads?

前端 未结 5 717
情深已故
情深已故 2020-12-29 07:31

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.

But I\'m probably wrong.

I\'m ju

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 08:20

    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:

    • Asynchronous operations
    • Operations that can be parallelized
    • Continual running background operations

提交回复
热议问题