Sobes.tech
Middle+

How is multithreading implemented in Node.js?

sobes.tech AI

Answer from AI

Node.js is inherently single-threaded for executing user JavaScript code. Concurrency is achieved through non-blocking I/O and the Event Loop. Multithreading for heavy tasks is implemented using the worker_threads module.

Event Loop:

  • The main mechanism for asynchronous operations.
  • A single-threaded cycle that handles callbacks related to I/O operations, timers, and other asynchronous events.

Worker Threads:

  • Allow parallel execution of CPU-bound heavy tasks.
  • Each worker runs its own V8 JavaScript engine in a separate thread.
  • Communication between the main thread and workers occurs via message passing (postMessage, receiveMessage).

Comparison:

Mechanism Purpose Parallelism State Isolation Memory Usage Complexity Best suited for
Event Loop Asynchronous I/O Concurrency Shared state Efficient Low I/O-bound tasks
Worker Threads CPU-bound computations Parallelism Isolated Higher Medium CPU-bound tasks

Example of using worker_threads:

// main.js
const { Worker, isMainThread, parentPort } = require('worker_threads');

if (isMainThread) {
  // Main thread
  const worker = new Worker(__filename); // Create a worker using the same file

  worker.on('message', (msg) => {
    console.log(`Message from worker: ${msg}`);
  });

  worker.on('error', (err) => {
    console.error(err);
  });

  worker.on('exit', (code) => {
    if (code !== 0)
      console.error(`Worker exited with code ${code}`);
  });

  worker.postMessage('Hello, worker!'); // Send message to worker

} else {
  // Worker thread
  parentPort.on('message', (msg) => {
    console.log(`Message from main thread: ${msg}`);
    parentPort.postMessage('Hello, main thread!'); // Send message back
  });
}

Event Loop is managed at the Node.js and libuv level, while worker_threads provide an API for explicit creation and management of threads for executing JavaScript code.

How is multithreading implemented in Node.js? — Node.js - sobes.tech