I am working on a Javascript simulator that runs in a web browser. It has a main loop:
do {
updateVisualization(simulator);
simulator.doStep();
} while (!reachedGoal(simulator));
And for every iteration, I need to run several workers that must be concurrently executed:
doStep = function() {
...
for (every agent in the simulation) {
var worker = new Worker('worker.js');
worker.onmessage = function(event) {
...
}
worker.postMessage(...);
}
// Here is the problem
}
My question is: how could I wait for every worker to finish?
A suggestion:
So all the action happens in the
onmessagecallback of the workers. Every time a worker responds with a message, you inspect thesimulator.workersarray by checking if all workers have afinishedproperty set totrue. If that is the case, this means that all workers finished and you can move on (the “survived for-loop” part).So basically, you instantiate all workers and then just wait for their responses… no loop required.