Skip to content

Proper function to calculate number of workers correctly #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion src/workerPools.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,19 @@ import WorkerPool from './WorkerPool';

const workerPools = Object.create(null);

function calculateNumberOfWorkers() {
// 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);
}

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,
Expand Down