Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Pool vs Thread Spawning

Can someone list some comparison points between Thread Spawning vs Thread Pooling, which one is better? Please consider the .NET framework as a reference implementation that supports both.

like image 710
reonze Avatar asked Jan 12 '10 15:01

reonze


People also ask

What is the difference between thread and thread pool?

A thread pool is a collection of threads which are assigned to perform uniformed tasks. The advantages of using thread pool pattern is that you can define how many threads is allowed to execute simultaneously.

What is thread spawning?

Spawning a thread in non-functional languages is considered a very low-level primitive. Often spawn or CreateThread takes a function pointer and an untyped (void) pointer to “data”.

When should you not use thread pool?

Thread pools do not make sense when you need thread which perform entirely dissimilar and unrelated actions, which cannot be considered "jobs"; e.g., One thread for GUI event handling, another for backend processing. Thread pools also don't make sense when processing forms a pipeline.

What is the meaning of thread pool?

A thread pool is a managed collection of threads that are available to perform tasks. Thread pools usually provide: Improved performance when executing large numbers of tasks due to reduced per-task invocation overhead. A means of bounding the resources, including threads, consumed when executing a collection of tasks.


1 Answers

Thread pool threads are much cheaper than a regular Thread, they pool the system resources required for threads. But they have a number of limitations that may make them unfit:

  • You cannot abort a threadpool thread
  • There is no easy way to detect that a threadpool completed, no Thread.Join()
  • There is no easy way to marshal exceptions from a threadpool thread
  • You cannot display any kind of UI on a threadpool thread beyond a message box
  • A threadpool thread should not run longer than a few seconds
  • A threadpool thread should not block for a long time

The latter two constraints are a side-effect of the threadpool scheduler, it tries to limit the number of active threads to the number of cores your CPU has available. This can cause long delays if you schedule many long running threads that block often.

Many other threadpool implementations have similar constraints, give or take.

like image 173
Hans Passant Avatar answered Sep 20 '22 08:09

Hans Passant