Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5/JS - Start several webworkers

I'm currently writing on a program, where I have to deal with huge arrays. I can however split those arrays. My plan now is, to process the arrays in different web workers. I have however never worked with them and do have several questions:

1. How would I run several web workers? I tried a for-loop looking like that:

for(i = 0; i < eD.threads; i++){
    //start workers here 
    var worker = new Worker("js/worker/imageValues.js");
    worker.postMessage(brightness, cD.pixels[i]);
}

Here I do get the error, that the object couldn't be cloned. Which seems logical. I guess it would be better to save them in an Array?

2. How would I control that all have finished their work? (I need to reassembly the array and work with it later)

3. How many web workers really bring an improvement?

4. Is there any advanced tutorial, besides the MDN-entry?

Thank you!

like image 864
stiller_leser Avatar asked Aug 12 '13 16:08

stiller_leser


People also ask

Can you have multiple web workers?

A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.

How many web workers can I create?

You can spawn as many workers as you wish. You can also pass data to the script being executed in the worker threads and also return value to the main thread upon completion.

Are web workers multithreaded?

Web workers give us the ability to write multi-threaded Javascript that doesn't block the DOM.

Can Webworkers access DOM?

Service workers — web workers in general — don't have direct access to the DOM at all. Instead, have the worker post the information to the main thread, and have code in the main thread update the DOM as appropriate.


1 Answers

1. How would I run several web workers? I tried a for-loop looking like that:

There's no problem with creating more than one worker, even if you don't keep track of them in an array. See below.

2. How would I control that all have finished their work? (I need to reassembly the array and work with it later)

They can post a message back to you when they're done, with the results. Example below.

3. How many web workers really bring an improvement?

How long is a piece of string? :-) The answer will depend entirely on the target machine on which this is running. A lot of people these days have four or more cores on their machines. Of course, the machine is doing a lot of other things as well. You'll have to tune for your target environment.

4. Is there any advanced tutorial, besides the MDN-entry?

There isn't a lot "advanced" about web workers. :-) I found this article was sufficient.

Here's an example running five workers and watching for them to be done:

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) { // <== There is no race condition here, see below
            display("All workers complete");
        }
    }
    function display(msg) {
        var p = document.createElement('p');
        p.innerHTML = String(msg);
        document.body.appendChild(p);
    }
})();

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 the race condition that doesn't exist: If you think in terms of true pre-emptive threading, then you might think: I could create a worker, increment running to 1, and then before I create the next worker I could get the message from the first one that it's done, decrement running to 0, and mistakenly think all the workers were done.

That can't happen in the environment web workers work in. Although the environment is welcome to start the worker as soon as it likes, and a worker could well finish before the code starting the workers finished, all that would do is queue a call to the workerDone function for the main JavaScript thread. There is no pre-empting. And so we know that all workers have been started before the first call to workerDone is actually executed. Thus, when running is 0, we know they're all finished.

Final note: In the above, I'm using onmessage = ... to hook up event handlers. Naturally that means I can only have one event handler on the object I'm doing that with. If you need to have multiple handlers for the message event, use addEventListener. All browsers that support web workers support addEventListener on them (youdon't have to worry about the IE attachEvent thing).

like image 187
T.J. Crowder Avatar answered Nov 15 '22 15:11

T.J. Crowder