是否有一个选项可以使主线程等待所有工作线程完成?
在下面的代码中,mainThread.js只是创建了worker。
工人要花很长时间执行。
在这种情况下,如何指示主线程等待所有线程执行完毕?
与Java中的thread.join()类似。
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)
执行:
node --experimental-worker mainThread.js
PS:我们可以尝试通过将其作为http服务器实例运行或使setTimeout具有很大的值来使其工作。 但是,nodejs本身是否有实现此问题的选项。