0.0.6 • Published 10 years ago

threadless v0.0.6

Weekly downloads
2
License
-
Repository
github
Last release
10 years ago

threadless

Threading for nodejs and the browser built on web workers

build status

Installation

This module is installed via npm:

$ npm install threadless

Background

Javascript can handle high level of concurrency by using it's single-threaded event-loop. This works as long as you don't have CPU intensive operations that block the loop and make your user-interface or server non-responsive.

However, Web Workers (or spawning a child process in node.js) allow you to run in another process/thread. This module provides a standard interface for running parallel tasks in node.js or in the browser. The node.js implementation works on workerjs.

Example Usage

var Thread = require('threadless');

// create a function for background execution
// NB: The function can't bind to any closures because it will be serialized
// and run in a Web Worker
var thread = new Thread(function (n, cb) {
  // CPU intensive operation that would block the event loop
  function fibo(n) {
    return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
  }

  cb(null, fibo(n));
});
// call the web worker thread with a value of 30
thread.run(30, function (err, result) {
  if (err) return done(err);
  expect(result).to.equal(1346269);
  done();
});

API

new Thread(fn)

Creates a new Thread instance based on the function passed in:

  • fn - The function that will be run in the background. Note that this function will get serialized so any closure references won't work. Any variables you want to pass through should go through the arguments.

thread.run(arg1, arg2, cb)

Runs the function in another thread with the following arguments.

  • arguments - list of arguments that will be passed to the thread function. the arguments can be functions, but they will be serialized before being sent to the thread function (so no closure scope will be passed).
  • cb - the callback that will be called by the thread function. Ie. the function must be asynchronous.

thread.kill()

Kills the thread.

0.0.6

10 years ago

0.0.5

10 years ago

0.0.4

10 years ago

0.0.3

10 years ago

0.0.2

10 years ago

0.0.1

10 years ago