From 0e265010f60c7a100a7e8267c9043768e657bea3 Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Fri, 14 Dec 2018 23:34:59 +0000 Subject: [PATCH 1/2] fix(NA): proper function to calculate number of workers correctly. --- README.md | 3 ++- src/workerPools.js | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f882b5d..ab278c8 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,8 @@ use: [ loader: "thread-loader", // loaders with equal options will share worker pools options: { - // the number of spawned workers, defaults to number of cpus + // the number of spawned workers, defaults to (number of cpus - 1) or + // fallback to 1 when require('os').cpus() is undefined workers: 2, // number of jobs a worker processes in parallel diff --git a/src/workerPools.js b/src/workerPools.js index 3a81b7a..730eb8b 100644 --- a/src/workerPools.js +++ b/src/workerPools.js @@ -3,10 +3,23 @@ import WorkerPool from './WorkerPool'; const workerPools = Object.create(null); +function calculateNumberOfWorkers() { + const cpus = os.cpus(); + + if (!cpus) { + // There are situations when this call will return undefined so + // we are fallback here to 1. + // More info on: https://github.com/nodejs/node/issues/19022 + return 1; + } + + return Math.max(1, cpus.length - 1); +} + function getPool(options) { const workerPoolOptions = { name: options.name || '', - numberOfWorkers: options.workers || os.cpus().length, + numberOfWorkers: options.workers || calculateNumberOfWorkers(), workerNodeArgs: options.workerNodeArgs, workerParallelJobs: options.workerParallelJobs || 20, poolTimeout: options.poolTimeout || 500, From cd2c4975015e4445bc4b1ee298d70bd14ed34720 Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Mon, 17 Dec 2018 11:19:22 +0000 Subject: [PATCH 2/2] refact(NA): apply simplication accordingly PR review. --- src/workerPools.js | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/workerPools.js b/src/workerPools.js index 730eb8b..a2204c5 100644 --- a/src/workerPools.js +++ b/src/workerPools.js @@ -4,14 +4,10 @@ import WorkerPool from './WorkerPool'; const workerPools = Object.create(null); function calculateNumberOfWorkers() { - const cpus = os.cpus(); - - if (!cpus) { - // There are situations when this call will return undefined so - // we are fallback here to 1. - // More info on: https://github.com/nodejs/node/issues/19022 - return 1; - } + // There are situations when this call will return undefined so + // we are fallback here to 1. + // More info on: https://github.com/nodejs/node/issues/19022 + const cpus = os.cpus() || { length: 1 }; return Math.max(1, cpus.length - 1); }