Junior — Middle
Explain the concept of a thread pool and its purpose in software systems.
sobes.tech AI
Answer from AI
Thread pool is a set of pre-created and ready-to-use threads that can be reused multiple times for executing tasks.
Purpose of a thread pool:
- To avoid the costs of creating and destroying threads for each task, which improves performance.
- To control the maximum number of threads running simultaneously to prevent system overload.
- To manage the task queue and distribute tasks among threads.
Example of usage in C# with ThreadPool:
using System;
using System.Threading;
class Program
{
static void Main()
{
ThreadPool.QueueUserWorkItem(state => {
Console.WriteLine("Task executed in thread pool.");
});
// Give time for the task to complete
Thread.Sleep(1000);
}
}
Thus, a thread pool helps efficiently manage multithreading and resources in an application.