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?!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With