Question

I'm experimenting with web workers, and was wondering how well they would deal with embarassingly parallell problems. I therefore implemented Connaway's Game of Life. (To have a bit more fun than doing a blur, or something. The problems would be the same in that case however.)

At the moment I have one web worker performing iterations and posting back new ImageData for the UI thread to place in my canvas. Works nicely.

My experiment doesn't end there however, cause I have several CPU's available and would like to parallellize my application.

So, to start off simply I split my data in two, down the middle, and make two workers each dealing with a half each. The problem is of course the split. Worker A needs one column of pixels from worker B and vice versa. Now, I can clearly fix this by letting my UI-thread give that column down to the workers, but it would be much better if my threads could pass them to eachother directly.

When splitting further, each worker would only have to keep track of it's neighbouring workers, and the UI thread would only be responsible for updating the UI (as it should be).

My problem is, I don't see how I can achieve this worker-to-worker communication. I tried handing the neighbours to eachother by way of an initialization postMessage, but that would copy my worker rather than hand down a reference, which luckily chrome warned me about being impossible.

Uncaught Error: DATA_CLONE_ERR: DOM Exception 25

Finally I see that there's something called a SharedWorker. Is this what I should look into, or is there a way to use the Worker that would solve my problem?

Was it helpful?

Solution

You should be able to use channel messaging:

var channel = new MessageChannel();
worker1.postMessage({code:"port"}, [channel.port1]);
worker2.postMessage({code:"port"}, [channel.port2]);

Then in your worker threads:

var xWorkerPort;
onmessage = function(event) {
    if (event.data.code == "port") {
        xWorkerPort = event.ports[0];
        xWorkerPort.onmessage = function(event) { /* do stuff */ };
    }
}

There's not much documentation around, but you could try this MS summary to get started.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top