threadless
Threading for nodejs and the browser built on web workers
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 = ;// 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 Workervar thread = {// CPU intensive operation that would block the event loop{return n > 1 ? + : 1;};};// call the web worker thread with a value of 30thread;
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.
Using with browserify
To use this in the browser, use the browserify command.
For example, for the following files:
<!-- app.html -->
// app.jsvar Thread = ;var thread = {// CPU intensive operation that would block the event loop{return n > 1 ? + : 1;};};thread;
Run the browserify command:
$ browserify app.js > bundle.js
Then open up app.html
in your browser.