Javascript:worker Synchronization
I am working on HTML5 web worker and I made a function that spawn few workers and return the result, but problem is that it returns the value before the worker updates the result.
Solution 1:
Like the comment points out - Web Workers work asynchronously (think of how AJAX works)
You can use an asynchronous semaphore to yield only when they're all done
functiondoSomething(callback){
var counter = array1_rows;
for (i = 0; i < array1_rows; i++)
{
var worker = newWorker('json.js');
worker.postMessage(arr1[i]);
worker.postMessage(arr2);
worker.postMessage(i);
worker.onmessage = function(){
storeResult.apply(arguments);//call it the same way it was called before.
counter--;
if(counter === 0){ // all workers returnedcallback(result); //or whatever you're updating in storeResult
}
};
}
}
Now you can call it like:
doSomething(function(result){
console.log(result); //this will print the correct result.
});
For more information about how JS async operations work I recommend this ajax related question that includes a description of the problem and how to approach it.,
Post a Comment for "Javascript:worker Synchronization"