Refactor spawnWorkers (#3338)
This commit is contained in:
parent
4a77548672
commit
168db6891f
36
src/index.ts
36
src/index.ts
@ -219,31 +219,21 @@ function checkMongoDb(config: Config) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function spawnWorkers(limit: number) {
|
async function spawnWorkers(limit: number) {
|
||||||
Logger.info('Starting workers...');
|
const workers = Math.min(limit, os.cpus().length);
|
||||||
|
Logger.info(`Starting ${workers} worker${workers === 1 ? '' : 's'}...`);
|
||||||
|
await Promise.all([...Array(workers)].map(spawnWorker));
|
||||||
|
Logger.succ('All workers started');
|
||||||
|
}
|
||||||
|
|
||||||
|
function spawnWorker(): Promise<void> {
|
||||||
return new Promise(res => {
|
return new Promise(res => {
|
||||||
// Count the machine's CPUs
|
const worker = cluster.fork();
|
||||||
const cpuCount = os.cpus().length;
|
worker.on('message', message => {
|
||||||
|
if (message !== 'ready') return;
|
||||||
const count = limit || cpuCount;
|
Logger.succ('A worker started');
|
||||||
let started = 0;
|
res();
|
||||||
|
});
|
||||||
// Create a worker for each CPU
|
|
||||||
for (let i = 0; i < count; i++) {
|
|
||||||
const worker = cluster.fork();
|
|
||||||
|
|
||||||
worker.on('message', message => {
|
|
||||||
if (message !== 'ready') return;
|
|
||||||
started++;
|
|
||||||
|
|
||||||
// When all workers started
|
|
||||||
if (started == count) {
|
|
||||||
Logger.succ('All workers started');
|
|
||||||
res();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user