Last active
February 9, 2022 11:20
-
-
Save mourjo/bc7b18b9b5854783f154838f078ab3a8 to your computer and use it in GitHub Desktop.
Concurrent Node.js workers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as nodeWorker from 'worker_threads'; | |
function sleep(ms) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, ms); | |
}); | |
} | |
async function doSomething(name) { | |
console.log(`${Date.now()}: Worker ${name} working ...`); | |
await sleep(Math.floor(10000)); | |
return Math.random() | |
} | |
if (nodeWorker.isMainThread) { | |
console.log("master: process id is " + process.pid); | |
const threads = new Set(); | |
threads.add(new nodeWorker.Worker('./workerdemo.js', { workerData: { name: "Tom" } })); | |
threads.add(new nodeWorker.Worker('./workerdemo.js', { workerData: { name: "Marvolo" } })); | |
threads.add(new nodeWorker.Worker('./workerdemo.js', { workerData: { name: "Riddle" } })); | |
for (let worker of threads) { | |
worker.on('error', (err) => { throw err; }); | |
worker.on('exit', () => { | |
threads.delete(worker); | |
console.log(`master: Thread exiting, ${threads.size} still running...`); | |
if (nodeWorker.size === 0) { | |
console.log(primes.join('\n')); | |
} | |
}) | |
worker.on('message', (msg) => { | |
console.log("master: Worker returned " + msg) | |
}); | |
} | |
for (let worker of threads) { | |
worker.postMessage('go'); | |
} | |
} else { | |
console.log(`worker: ${nodeWorker.workerData.name} process id is ` + process.pid); | |
nodeWorker.parentPort.on('message', async (msg) => { | |
const d = await doSomething(nodeWorker.workerData.name); | |
nodeWorker.parentPort.postMessage(`${nodeWorker.workerData.name} computed result ${d}`); | |
process.exit(); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment