Nearby lessons

19 of 21

🧵 Node.js – Thread Pool & Libuv

📌 What is Thread Pool?

What is Thread Pool in Node.js?

Node.js runs on a single-threaded event loop, but behind the scenes, Libuv manages a pool of threads to handle asynchronous, time-consuming tasks. This allows Node.js to perform non-blocking I/O efficiently.

💬 Conversation between Main Thread and Libuv Thread Pool

  • Main Thread To Libuv: Hello Libuv, I want to read file content but this is time consuming. Can I pass this task to you?
  • Libuv Thread Pool To Main Thread: Sure, main thread. I have multiple threads to handle time-consuming tasks. Once the task is done, the file content is retrieved and the callback function runs.

📄 Example – Asynchronous File Read

Node.js Environment
RUNTIME ACTIVE
const fs = require('fs');

console.log("Before...");

fs.readFile("./info.txt", "utf-8", (err, data) => {
    if(err) throw err;
    console.log("File Content");
});

console.log("After...");
Terminal Output
Live Output Preview

🟢 About Libuv

  • Libuv is written in C language and uses the system kernel which has multiple threads.
  • Node.js itself is single-threaded, but Libuv's thread pool implements multiple threads behind the scenes.
  • Libuv provides the concept of non-blocking I/O, allowing Node.js to perform asynchronous operations efficiently.

🔹 What is Libuv?

  • A cross-platform open-source library written in C.
  • Handles asynchronous non-blocking operations in Node.js.

⚡ Non-Blocking Tasks in Node.js

  • Thread Pool – Handles CPU-intensive tasks asynchronously.
  • Event Loop – Handles I/O operations without blocking the main thread.

🔹 Experiments to Understand Thread Pool

  • Experiment 1: Methods with 'sync' suffix run on the main thread and are blocking.
  • Experiment 2: Async methods like fs.readFile() run in Libuv's thread pool, appearing asynchronous from the main thread’s perspective.

🔹 Thread Pool Size

  • Libuv's thread pool has 4 threads by default.
  • The thread pool size can be increased, but should ideally match the system’s CPU cores for optimal performance.
  • Increasing the thread pool size can improve performance for multiple async calls, e.g., pbkdf2.

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!Network I/O in Node.js