1. How can I run multiple web workers? I tried a loop like this:
There is no problem creating more than one worker, even if you do not track them in an array. See below.
2. How can I control that everyone has finished their work? (I need to reassemble the array and work with it later)
They can send a message to you when they are done, with the results. An example is below.
3. How many web workers really bring improvement?
How long does the line last? :-) The answer will depend entirely on the target machine on which it runs. Many people these days have four or more cores on their machines. Of course, a machine does many other things. You will need to set up your target environment.
4. Is there any extended tutorial besides the MDN record?
There are not many βadvancedβ about web workers. :-) I found this article .
Here is an example in which five workers work and oversee them:
Main window:
(function() { var n, worker, running; display("Starting workers..."); running = 0; for (n = 0; n < 5; ++n) { workers = new Worker("worker.js"); workers.onmessage = workerDone; workers.postMessage({id: n, count: 10000}); ++running; } function workerDone(e) { --running; display("Worker " + e.data.id + " is done, result: " + e.data.sum); if (running === 0) {
worker.js :
this.onmessage = function(e) { var sum, n; sum = 0; for (n = 0; n < e.data.count; ++n) { sum += n; } this.postMessage({id: e.data.id, sum: sum}); };
About a race condition that does not exist: if you are thinking of a true preemptive flow, you might think: I could create a worker, increase running to 1 , and then before I create the next worker I could get a message from the first that he did by decreasing running to 0 and mistakenly thought that all workers were done.
This cannot happen in the environment in which web workers work. Although the environment is welcome to start work as soon as it wants, and the worker may well finish before the code that starts the workers is finished, all that could be done is the queues for calling the workerDone function for the main JavaScript thread. Anticipation does not exist. And therefore, we know that all workers were started before the first call to workerDone . Thus, when running 0 , we know that they are all complete.
Final note. In the above example, I use onmessage = ... to connect event handlers. Naturally, this means that I can have only one event handler for the object with which I am doing this. If you need to have multiple handlers for the message event, use addEventListener . All browsers that support web workers support addEventListener on them (you don't need to worry about attachEvent IE).