const { Worker, isMainThread, parentPort } = require("worker_threads");
if (isMainThread) {
const worker = new Worker(__filename);
worker.on("message", (message) => console.log("from worker", message));
worker.on("exit", () => console.log("worker exit"));
worker.postMessage("ping");
} else {
parentPort.on("message", (value) => {
console.log("from parent", value);
parentPort.postMessage("pong");
parentPort.close();
});
}
const {
Worker,
isMainThread,
parentPort,
workerData,
} = require("worker_threads");
const threads = new Set();
threads.add(
new Worker(__dirname + "/employee1.js", {
workerData: { number: 999 },
})
);
threads.add(
new Worker(__dirname + "/employee2.js", {
workerData: { number: 666 },
})
);
for (let worker of threads) {
worker.on("message", (message) => console.log("from worker", message));
worker.on("exit", () => {
threads.delete(worker);
if (threads.size === 0) {
console.log("job done! threads.size === ", threads.size);
}
});
}
const { workerData, parentPort } = require("worker_threads");
const data = workerData;
console.log("data from 1: ", data);
parentPort.postMessage(data.number / 3);
const { workerData, parentPort } = require("worker_threads");
const data = workerData;
parentPort.postMessage(data.number / 999);