title: Number of threads Workers in NodeJS will spawn
body: <p>I am trying to understand the working of workers in NodeJS.
  My understanding is everytime we spawn a worker , it will create a new thread with it own Node/V8 instance.</p>
  
  <p>So will the below code spawn 50 threads?</p>
  
  <p>How is it distributed over the cpu cores?</p>
  
  <p>This is the index.js</p>
  
  <pre><code>const { Worker } = require("worker_threads");
  var count = 0;
  
  console.log("Start Program");
  
  const runService = () =&gt; {
    return new Promise((resolve, reject) =&gt; {
      const worker = new Worker("./service.js", {});
      worker.on("message", resolve);
      worker.on("error", reject);
      worker.on("exit", code =&gt; {
        if (code != 0) {
          reject(new Error("Worker has stopped"));
        }
      });
    });
  };
  
  const run = async () =&gt; {
    const result = await runService();
    console.log(count++);
    console.log(result);
  };
  
  for (let i = 0; i &lt; 50; i++) {
    run().catch(error =&gt; console.log(error));
  }
  
  setTimeout(() =&gt; console.log("End Program"), 2000);
  </code></pre>
  
  <p>and this is the service.js file</p>
  
  <pre><code>const { workerData, parentPort } = require("worker_threads");
  
  // You can do any heavy stuff here, in a synchronous way
  // without blocking the "main thread"
  const sleep = () =&gt; {
    return new Promise(resolve =&gt; setTimeout(() =&gt; resolve, 500));
  };
  let cnt = 0;
  for (let i = 0; i &lt; 10e8; i += 1) {
    cnt += 1;
  }
  parentPort.postMessage({ data: cnt });
  </code></pre>