Junior — Middle
Can you explain what a thread pool is and how it works?
sobes.tech AI
Answer from AI
A thread pool is a collection of pre-created threads that are reused to perform tasks, instead of creating a new thread for each task. This improves performance and reduces the overhead of creating and destroying threads.
How it works:
- A fixed or dynamic number of threads is created when the program starts.
- Tasks are placed in a queue.
- An available thread from the pool takes a task from the queue and executes it.
- After completing the task, the thread returns to the pool and waits for the next task.
In Node.js, although the main thread is single-threaded, a thread pool is used for executing input/output operations and other asynchronous tasks (via libuv). This allows the main thread to remain unblocked and efficiently handle many requests.
Example of creating a thread pool in Node.js using the worker_threads module:
const { Worker } = require('worker_threads');
function runService(workerData) {
return new Promise((resolve, reject) => {
const worker = new Worker('./worker.js', { workerData });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0)
reject(new Error(`Worker stopped with exit code ${code}`));
});
});
}
// You can create a pool of several such workers and distribute tasks among them
Thus, a thread pool helps efficiently manage resources and improve application performance.