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.
So will the below code spawn 50 threads?
How is it distributed over the cpu cores?
This is the index.js
const { Worker } = require("worker_threads");
var count = 0;
console.log("Start Program");
const runService = () => {
return new Promise((resolve, reject) => {
const worker = new Worker("./service.js", {});
worker.on("message", resolve);
worker.on("error", reject);
worker.on("exit", code => {
if (code != 0) {
reject(new Error("Worker has stopped"));
}
});
});
};
const run = async () => {
const result = await runService();
console.log(count++);
console.log(result);
};
for (let i = 0; i < 50; i++) {
run().catch(error => console.log(error));
}
setTimeout(() => console.log("End Program"), 2000);
and this is the service.js file
const { workerData, parentPort } = require("worker_threads");
// You can do any heavy stuff here, in a synchronous way
// without blocking the "main thread"
const sleep = () => {
return new Promise(resolve => setTimeout(() => resolve, 500));
};
let cnt = 0;
for (let i = 0; i < 10e8; i += 1) {
cnt += 1;
}
parentPort.postMessage({ data: cnt });