Skip to content Skip to sidebar Skip to footer

How To Wait For Multiple Webworkers In A Loop

I have the following issue with Web Workers in JS. I have a heavy duty application doing some simulation. The code runs in multiple Web Workers. The main thread is running on a We

Solution 1:

I would love to have a blocking function like myWebWorker.waitForReady()

No, that's not possible. All the statements you researched are correct, web workers stay asynchronous and will only communicate by messages. There is no waiting for events, not even on worker threads.

You will want to use promises for this:

functioncreateWorkers(workerCount, src) {
    var workers = newArray(workerCount);
    for (var i = 0; i < workerCount; i++) {
        workers[i] = newWorker(src);
    }
    return workers;
}
functiondoWork(worker, data) {
    returnnewPromise(function(resolve, reject) {
        worker.onmessage = resolve;
        worker.postMessage(data);
    });
}
functiondoDistributedWork(workers, data) {
    // data size is always a multiple of the number of workersvar elementsPerWorker = data.length / workers.length;
    returnPromise.all(workers.map(function(worker, index) {
        var start = index * elementsPerWorker;
        returndoWork(worker, data.slice(start, start+elementsPerWorker));
    }));
}

var myWebWorkers = createWorkers(8, 'worker.js');
var somedata = [...];
functionstep(i) {
    if (i <= 0)
        returnPromise.resolve("done!");
    returndoDistributedWork(myWebWorkers, somedata)
    .then(function(results) {
        if (i % 100)
            updateSVGonWebPage();
        returnstep(i-1)
    });
}
step(1000).then(console.log);

Promise.all does the magic of waiting for concurrently running results, and the step function does the asynchronous looping using a recursive approach.

Post a Comment for "How To Wait For Multiple Webworkers In A Loop"