javascript - Web workers - How do they work? -
i'm trying understand this example:
html (main code):
<html> <title>test threads fibonacci</title> <body> <div id="result"></div> <script language="javascript"> var worker = new worker("fibonacci.js"); worker.onmessage = function(event) { document.getelementbyid("result").textcontent = event.data; dump("got: " + event.data + "\n"); }; worker.onerror = function(error) { dump("worker error: " + error.message + "\n"); throw error; }; worker.postmessage("5"); </script> </body> </html>
javascript (worker code):
var results = []; function resultreceiver(event) { results.push(parseint(event.data)); if (results.length == 2) { postmessage(results[0] + results[1]); } } function errorreceiver(event) { throw event.data; } onmessage = function(event) { var n = parseint(event.data); if (n == 0 || n == 1) { postmessage(n); return; } (var = 1; <= 2; i++) { var worker = new worker("fibonacci.js"); worker.onmessage = resultreceiver; worker.onerror = errorreceiver; worker.postmessage(n - i); } };
i have following questions:
when worker code starts run ? after execution of
var worker = new worker("fibonacci.js");
?is true
onmessage = function(event) { ... }
assignment in worker code executed beforeworker.postmessage("5");
in main code ?can worker code access global variables defined in main code (like
worker
)?can main code access global variables defined in worker code (like
results
)?it seems me
worker.onmessage = function(event) {...}
in main code has same meaningonmessage = function(event) {...}
in worker code (whichonmessage
event handler of worker). wrong ? difference between them ?what code should ? when run here prints "5". supposed do, or i'm missing ?
thanks lot !
check out html5 rocks: basics of web workers general tutorial.
- workers start call
postmessage
method of worker. - the function bound worker's
onmessage
in main code work when worker callspostmessage
. - global variables not shared between main , worker threads. way pass data through messaging via
postmessage
. - as suspected,
onmessage
on both worker , main code has same meaning. event handler when thread receives message event. can useaddeventlistener
instead, catchingmessage
event:
main code:
function showresult(event) { document.getelementbyid("result").textcontent = event.data; dump("got: " + event.data + "\n"); } var worker = new worker("fibonacci.js"); worker.addeventlistener('message', showresult, false);
worker code:
addeventlistener('message', resultreceiver, false);
the fibonacci example took recursive worker example. if not using workers, this:
function fibonacci(n) { if (n == 0 || n == 1) return n; return fibonacci(n-1) + fibonacci(n-2); } var result = fibonacci(5); dump("got: " + result + "\n");
(oh no, i'm not going stackless you. write yourself!)
Comments
Post a Comment