views:

32

answers:

2

Please consider the following code and the explanation from this Mozilla tutorial "Using web workers":

var myWorker = new Worker('my_worker.js');
myWorker.onmessage = function(event) {
  print("Called back by the worker!\n");
};

Line 1 in this example creates and starts running the worker thread. Line 2 sets the onmessage handler for the worker to a function that is called when the worker calls its own postMessage() function.

The thread is started in the moment the Worker constructor is called. I wonder if there might be a race-condition on setting the onmessage handler. For example if the web worker posts a message before onmessage is set.

Does someone know more about this?

Update:

Andrey pointed out that the web worker should start its work, when it receives a message, like in the Fibonacci example in the Mozilla tutorial. But doesn't that create a new race-condition on setting the onmessage handler in the web worker?

For example:

The main script:

var myWorker = new Worker('worker.js');
myWorker.onmessage = function(evt) {..};
myWorker.postMessage('start');

The web worker script ('worker.js')

var result = [];
onmessage = function(evt) {..};

And then consider the following execution path:

main thread                                  web worker
var worker = new Worker("worker.js");
                                             var result = [];
myWorker.onmessage = ..
myWorker.postMessage('start');
                                             onmessage = ..

The "var result = []" line can be left out, it will still be the same effect.

And this is a valid execution path, I tried it out by setting a timeout in the web worker! At the moment I can not see, how to use web workers without running into race-conditions?!

+1  A: 

Yes, it is possible to cause race condition here. The responsibility lies on developer of Worker. It should start posting messages only after it receives message via postMessage(). In constructor it must only do initialization, but not actual processing. In Examples section from your page there is nice sample about fibonachi numbers. Look at it's structure, the real work starts when message is received. Follow that pattern.

Andrey
What if the main thread sends its start message, before the web worker has set its onmessage handler? Is that possible?
toobb
A: 

The answer is that both the main script and the web worker have a MessagePort queue which collects the messages before the initial worker script returns.

For details, see this thread on the WHATWG help mailing list: http://lists.whatwg.org/pipermail/help-whatwg.org/2010-August/000606.html

toobb