Browse files

Fibonacci worker example from https://developer.mozilla.org/En/Using_…

  • Loading branch information...
1 parent a0b5ec1 commit 4eb47f95f1a3a8aae052654c1294dfda2b58b173 Tom Robinson committed Oct 9, 2009
Showing with 54 additions and 0 deletions.
  1. +35 −0 examples/fibonacci-worker.js
  2. +19 −0 examples/fibonacci.js
View
35 examples/fibonacci-worker.js
@@ -0,0 +1,35 @@
+// Adapted from https://developer.mozilla.org/En/Using_web_workers
+
+var Worker = require("worker").Worker;
+
+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;
+ }
+
+ for (var i = 1; i <= 2; i++) {
+ var worker = new Worker(module.path);
+ worker.onmessage = resultReceiver;
+ worker.onerror = errorReceiver;
+ worker.postMessage(n - i);
+ }
+};
+
+if (module.id == require.main)
+ print("Run fibonacci.js instead of fibonacci-worker.js");
View
19 examples/fibonacci.js
@@ -0,0 +1,19 @@
+// Adapted from https://developer.mozilla.org/En/Using_web_workers
+
+var FILE = require("file"),
+ Worker = require("worker").Worker;
+
+var worker = new Worker(FILE.join(FILE.dirname(module.path), "fibonacci-worker.js"));
+
+worker.onmessage = function(event) {
+ print("Got: " + event.data);
+}
+
+worker.onerror = function(error) {
+ print("Worker error: " + error.message);
+}
+
+worker.postMessage(5);
+
+// event loop
+while(true) require("event-queue").nextEvent()();

0 comments on commit 4eb47f9

Please sign in to comment.