Search code examples
javascriptweb-worker

Create a dynamic number of web workers Javascript


I am working on a performance heavy app, where the workload can easily be subdivided into web workers.

However because of different consumer hardware I won't know the optimal number of workers until runtime. At runtime I can find the optimal number using navigator.hardwareConcurrency.

My problem is I can't think of a way to spawn an unknown number of workers. If I wanted to spawn 3 web workers for example I could do this:

var worker0 = new Worker("workerScript.js");
var worker1 = new Worker("workerScript.js");
var worker2 = new Worker("workerScript.js");

Is there a way to spawn and listen for events from "x" number of workers?


Solution

  • There's an example in MDN

    let workerList = [];
    
    for (let i = 0; i < window.navigator.hardwareConcurrency; i++) {
      let newWorker = {
        worker: new Worker('cpuworker.js'),
        inUse: false
      };
      workerList.push(newWorker);
    }