Search code examples
javascriptnode.jsbackendthreadpoolevent-loop

why process.env.UV_THREADPOOL_SIZE doesn't work?


const crypto = require("crypto");
const start = Date.now();
process.env.UV_THREADPOOL_SIZE = 5;
for (let index = 0; index < 5; index++) {
  crypto.pbkdf2("password", "salt", 100000, 512, "sha512", () => {
    console.log(Date.now() - start);
  });
}

/* outputs 1429 1518 1521 1537 2289

*/ ` // the outputs don't seem to expected outputs. what is problem ?


Solution

  • This is the expected behavior.

    NodeJS has a limited number of threads to handle those tasks, and even if you have 5 tasks and 5 threads in the pool, they don't all run simultaneously. Instead, they run in a somewhat sequential manner due to the limited thread pool size. Also, each task's completion time varies depending on your system's workload and how the thread pool manages the tasks.

    I also encourage you to check the Worker Threads as it allows you to create multiple threads explicitly and better for parallelism.