Junior — Middle
Can you explain what Worker Threads in Node.js are and how they are used for multithreading?
sobes.tech AI
Answer from AI
In Node.js, Worker Threads is a module that allows creating separate threads to execute JavaScript code in parallel with the main thread. By default, Node.js operates in a single-threaded mode, which is good for I/O but inefficient for CPU-intensive tasks.
Worker Threads create full-fledged threads that can perform computations without blocking the main event loop. They communicate with the main thread via messages (postMessage and on('message')).
Example usage:
const { Worker, isMainThread, parentPort } = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', msg => console.log('From worker:', msg));
worker.postMessage('Hello, worker!');
} else {
parentPort.on('message', msg => {
parentPort.postMessage(`Received: ${msg}`);
});
}
Thus, Worker Threads enable efficient parallelization of tasks in Node.js, improving performance for computations.