Is there an option by which we can make the main thread wait until all worker threads are done?
In the below code, mainThread.js simply creates workers.
The worker takes long time to execute.
In this situation, how do we instruct the main thread to wait till all threads are done with execution?
Something similar to thread.join() in java.
mainThread.js:
const {Worker, parentPort, workerData} = require('worker_threads');
const path = require('path');
const startWorker = function(path, workerData, callback) {
//Create worker thread
let worker = new Worker(path, {workerData});
//Listen to events of the worker thread
worker.on('message', (msg) => {
callback(null, msg);
});
worker.on('error', callback);
worker.on('exit', (code) => {
if(code !== 0) {
console.error(`Error: Non-zero exit code ${code}`)
}
});
//Return the worker thread
return worker;
};
console.log('This is Main Thread');
//Create and start worker threads
let thread1 = startWorker(__dirname + path.sep + 'workerThread.js', "user1", (error, result) => {
if(error) return console.error(error);
console.log('Result: ', result);
});
let thread2 = startWorker(__dirname + path.sep + 'workerThread.js', "user2", (error, result) => {
if(error) return console.error(error);
console.log('Result: ', result);
});
workerThread.js:
const {workerData, parentPort} = require('worker_threads');
setTimeout(() => {
console.log(workerData);
parentPort.postMessage(workerData + "done");
}, 2000)
Execution:
node --experimental-worker mainThread.js
PS: We can try to make it work by running it as an http server instance or by having a setTimeout with a huge value. But, is there an option by nodejs itself to achieve it is the question.
worker.on('message',
do ->worker.once('message'
But saying that it's not the best way, making this into a thread pool would be better. – Semolina