thread.js 
thread.js is lightweight, reliable and rich featured library that
simplifies JavaScript parallel computing in browser environments
through a clean and elegant promise-based API.
You can run tasks in real threads in a really simple way,
with an elegant programatic aproach and graceful state handling
It provides useful features such as data binding serialization, cross-scope arguments passing, asynchronous tasks, require external scripts in the thread and includes built-in support to create a pool of threads to distribute multiple background
tasks across multiple workers transparently using a simple task load availability algorithm
It uses Web Workers to create real threads,
but provides fallback support for older browsers based on an iframe hack (now you can be safe in IE9 and other older browsers)
Welcome to the multithreading world in the browser, now made simple, funny and small (5KB gzipped)
Getting started with basic usage,
some examples or tests and be aware about threads limitations
Installation
Via Bower
bower install thread
Via Component
component install h2non/thread.js
Or loading the script remotely
<script src="//cdn.rawgit.com/h2non/thread.js/0.1.16/thread.js"></script>
Browser Support
Basic usage
If require is available, you must use it to fetch the module.
Otherwise it will be available as global
var thread = require('thread')
Create a new thread with custom scope environment and import external libraries
var worker = thread({
env: { numbers: [1,2,3] },
require: [
'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js'
]
})
Running a synchronous task in the thread
var task = worker.run(function () {
return _.sortBy(env.numbers, function (num) {
return Math.sin(num)
})
})
Running an asynchronous task in the thread
var task = worker.run(function (done) {
doAsyncStuff(function () {
var sorted = _.sortBy(env.numbers, function (num) {
return Math.sin(num)
})
done(null, sorted)
})
})
Consuming the computed result (promise-based API)
task.then(function (array) {
console.log(array) // -> [3, 1, 2]
}).catch(function (err) {
console.log('Ups:', err.message)
}).finally(function (result) {
console.log('Final result:', result) // -> [3, 1, 2]
})
Note about Internet Explorer usage
Since Microsoft makes a continuous effort to break the Web and its standards, due to a technical limitation in IE 10 and 11,
it is required to use an external script to create the thread properly.
You must customize the evalPath option when creating threads from IE.
The eval script is located in lib/eval.js
Common example with Bower:
var worker = thread({
evalPath: '/bower_components/thread.js/lib/eval.js' // default 'lib/eval.js'
})
If you use full URLs to load the eval script, be aware about cross-origin policy.
You must define the CORS headers properly in the server
Web Workers resources
Web Worker limitations
You should be aware of some limitations while using Web Worker (aka threads)
Web Workers are by design strongly isolated.
That means each worker has its own isolated scope and memory stack space.
In other words, you must explicitly bind values or functions
to the thread in order to have access and consum them inside the worker scope.
Any passed value to the thread scope will be cloned (it will be passed by value, not by reference),
so mutation is not possible between scopes since memory space has no synchronization
If you create a pool of threads, you must consider that threads in the pool are scope-isolated too.
In other words, it's not supported scope synchronization between threads in the pool.
That's usually positive because you cannot have side-effects between threads,
but you should be aware about global scope dependencies and mutation in your code in other to avoid inconsistency between threads
All values binded to the thread must be JSON-serializable, meaning only primitives types, raw objects and functions.
Same with return values from threads.
In modern browsers, there is possible to bind complex data type structures to the Worker scope using the Transferable interface which supports the internal structure cloning algorithm.
However, there are still some limitations: DOM nodes, native built-in functions and prototypes chains cannot be cloned and therefore, is not possible to bind them to the thread
Additionally, threads do not have access to the DOM API
API
thread([options])
Return: thread Alias: thread.create
Supported options:
- env
object Custom environment to bind to the isolated thread scope
- require
string|array|object Source path scripts to load or map of values/functions to bind
- namespace
string Global namespace to allocate the scope environment. Default to env
- evalPath
string Path to eval.js script, required in IE 10 & 11. Default to lib/eval.js
- silent
boolean Enable/disable silent mode. If enabled, Worker errors will not throw an exception and you should subscribe to the error event to handle them properly. Default false
thread({
namespace: 'global',
env: {
x: 10,
sqrt: function (n) {
return Math.sqrt(Math.pow(n, n))
}
},
require: [
'http://cdn.rawgit.com/h2non/hu/0.1.1/hu.js'
]
})
thread#run(fn, env, args)
Return: task Alias: exec
Run the given function in the thread.
You can optionally bind a custom context (as map of values) or passing function arguments
(as array) to be injected when the function will be invoked
Bind values must be serializable types (see threads limitations)
Run a function and return the result synchronously (return statement required)
thread().run(function () {
return 2 * 2
}).then(function (result) {
console.log(result) // -> 4
})
Binding a custom context and return the result asynchronously
thread().run(function (done) {
done(null, this.x * 2)
}, { x: 2 }).then(function (result) {
console.log(result) // -> 4
})
Passing arguments and return the result asynchronously
thread().run(function (num, done) {
done(null, num * this.x)
}, { x: 2 }, [ 2 ]).then(function (result) {
console.log(result) // -> 4
})
thread#pool(number)
Return: thread
Create a pool of a maximum number of threads and run tasks across them
It implements a simple best availability scheudle algorithm to transparently
distribute tasks across multiple workers.
It will only create a new thread if it's required and there is not any other thread available
This feature is still beta and major improvements will be done in future releases.
Any feedback will be really appreciated
// create a pool with a maximum of 10 threads
var pool = thread({ env: { users: 2 } }).pool(10)
var count = 1
var maxTasks = 50
function runAsyncTask(num) {
pool.run(function (done) {
countUsers(function (usersLength) {
done(null, env.users + usersLength)
})
}).then(function (result) {
console.log('Task:', num)
console.log('Result:', result)
console.log('Used threads:', pool.threadPool.length)
if (count++ === maxTasks) {
console.log('Tasks finished')
pool.kill() // kill all the threads in the pool
}
})
}, Math.random() * 1000)
}
while (var i = 0; i < maxTasks) {
i += 1
runAsyncTask(i)
}
thread#bind(obj)
Return: thread Alias: set
Bind a map of values to the isolated thread scope.
You can do the same passing an object via thread#require()
Passed values will be exposed in the global namespace (default to env)
var task = thread().bind({
num: 4,
list: [3,2,1],
defer: function (fn) {
setTimeout(fn, 1)
}
})
task.run(function (done) {
env.defer(function () {
done(null, env.list.reverse().push(env.num))
})
}).then(function (result) {
console.log(result) // -> [1,2,3,4]
})
thread#require(sources)
Return: thread Alias: import
Load remote scripts from a valid URL, bind an object or functions to the thread isolated scope.
Passed values will be exposed in the global namespace (default to env)
Importing a remote script
thread()
.require('http://cdn.rawgit.com/h2non/hu/0.1.1/hu.js')
.run(function () {
return typeof hu === 'object'
}).then(function (exists) {
console.log(exists) // -> true
})
Or multiple scripts
thread().require([
'http://cdn.rawgit.com/h2non/hu/0.1.1/hu.js',
'http://cdn.rawgit.com/h2non/fw/0.1.2/fw.js'
])
Binding custom objects and primitives types (does the same as bind())
thread().require({
list: [1,2,3,4,5],
name: 'John',
age: 28,
time: new Date().getTime()
})
Binding functions
thread().require({
defer: function (fn) {
setTimeout(fn, 1)
},
transform: function (arr) {
return arr.reverse().filter(function (num) {
return num > 1 && num < 100
})
}
})
Bind values will be available in the global namespace object (default to env)
thread#flush()
Return: thread
Flush the thread cached memory and scope environment.
var worker = thread({ env: { x: 2 } })
console.log(Object.keys(worker.options.env).length) // -> 1
worker.flush()
console.log(Object.keys(worker.options.env).length) // -> 0
thread#flushTasks()
Return: thread
Flush running tasks promises and clean cached values
var worker = thread()
worker.run(longThreadTask)
console.log(worker.pending()) // -> 1
worker.flushTasks()
console.log(worker.pending()) // -> 0
thread#send(msg)
Return: thread
Send a message directly to the current thread.
Useful for specific use cases, but it's preferably do not use it directly.
Use the run() abstraction instead
Be aware about passing non-serialize data types such as native JavaScript objects,
DOM nodes, objects with self-references... (see threads limitations)
var worker = thread()
worker.send({ type: 'msg', data: 'hello world' })
thread#kill()
Return: thread Alias: terminate
Kill the current thread. All the cached data, scope environment and config options will be flushed,
including in worker isolated scope
It's recommended you explicit kill any unused thread in order to avoid memory issues in long term computations
var worker = thread()
worker.run(longTask).then(function () {
worker.kill()
})
thread#start([options])
Return: thread
Start (or restart) the current thread.
If the thread was previously killed, you can reuse it calling this method
var options = { env: { x: 2 } }
var worker = thread(options)
worker.kill() // explicit kill
worker.start(options) // explicit re-start, passing the same options
thread#pending()
Return: number
Return the pending running tasks on the current thread
var worker = thread()
var task = worker.run(longAsyncTask)
worker.pending() // -> 1
task.then(function () {
worker.pending() // -> 0
})
thread#running()
Return: boolean
Return true if the current thread has running tasks
thread().run(longAsyncTask).running() // -> true
thread().run(tinySyncTask).running() // -> false