Advertisement
Guest User

malte

a guest
Dec 7th, 2009
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // server.js
  2. var sys = require('sys'),
  3.    http = require('http'),
  4.    Worker = require('worker').Worker;
  5.  
  6. var WORKER_COUNT = 4;
  7. var responses = {};
  8.  
  9. var pool = [];
  10. for (var i = 0; i < WORKER_COUNT; ++i) {
  11.   var worker = new Worker("./child.js");
  12.   worker.addListener("message", function (msg) {
  13.     var res = responses[msg.call];
  14.     delete responses[msg.call];
  15.     res.sendHeader(200, {'Content-Type': 'text/plain'});
  16.     res.sendBody(msg.data+"");
  17.     res.finish();
  18.   });
  19.   worker.addListener("error", function (error) {
  20.     sys.puts("Worker error "+error)
  21.   })
  22.   pool.push(worker);
  23.   sys.puts('Started worker process.');
  24. }
  25.  
  26. var call = 0;
  27. http.createServer(function (req, res) {
  28.   var worker = pool[ call % pool.length ];
  29.   worker.postMessage({
  30.     call: call,
  31.     request: req.uri
  32.   });
  33.   responses[call] = res;
  34.   sys.puts("Send call " + call);
  35.   ++call;
  36.  
  37. }).listen(8000);
  38. sys.puts('Server running at http://127.0.0.1:8000/');
  39.  
  40. // child.js
  41. var sys    = require('sys');
  42. var worker = require('worker').worker;
  43.  
  44. worker.onmessage = function (msg) {
  45.   sys.error("HANDLE");
  46.   worker.postMessage({
  47.     call: msg.call,
  48.     data: fib( parseInt( msg.request.params.n, 10 ) )
  49.   })
  50. }
  51.  
  52. function fib(n) {
  53.   return n < 2 ? n : fib(n-1)+fib(n-2);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement