6
I have a page where I intend to use a set of Webworkers to perform tasks in the background. Each Webworker has a specific function, but potentially useful to others. It is simple to receive/send messages from/to a Webworker created by page (or created by a specific Webworker in the case of sub-Workers), as there is a reference to the Worker
in which one can add listeners or call methods:
var worker1 = new Worker("script1.js");
worker1.postMessage("bla");
worker1.onmessage = function(mensagem) {
alert(mensagem.data);
};
var worker2 = new Worker("script2.js");
...
But if, say, the script1.js
want to send a message to worker2
, it is possible to do so without "routing" the message through the thread main? (i.e. the onmessage
of worker1
receives the message and makes a postMessage
pro worker2
)
The reason is performance: as the HTML5 Web Messaging serializes the message parameters (and at the time of writing most browsers still do not support Transferable
s), this "routing" would require the data to be serialized and de-serialized twice, although the overhead if sending two messages were negligible (which is not always true, since certain applications - Webgl for example - can maintain the thread main occupied for a long time).
Have you investigated the use of Shared Workers? I know their support is currently limited to Chrome, Safari and Opera, but you could implement a Shim to make it work on Firefox and IE...
– Marco Aurélio
@I’m reading about Shared Workers, and it looks promising. I’m going to try to create a proof of concept. I just have my doubts whether it would be possible to create a Shim that did not suffer from the performance problems mentioned above...
– mgibsonbr
The Shim would probably suffer from the same performance problems. : ( But at least it would work. Another thing to consider is using JSON.stringify() and JSON.parse() to do serialization and deserialization manually on the sending worker and the receiving worker, so you save serialization operations. (I suppose strings are passed intact, since they are immutable and can be shared by threads in theory.)
– Marco Aurélio