Sunday, January 17, 2016

Multi-threading in JavaScript with ParallelJS


Parallel.js is a simple library for parallel computing in Javascript (in node.js or in the modern web browsers). Paralleljs takes advantage of Web Workers for the web, and child processes for Node.

What is web workers

Web Workers are a mechanism by which a script operation can be made to run in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.
- https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API 


Multi-Threading in JavaScript

JavaScript is executed in a single thread by an event loop. With the Worker interface, a solution to this single-thread limitation problem has been found. With web workers Messages Api is used to communicate.

Note that, multi-threaded programming is parallel, but parallel programming is not necessarily multi-threaded. Unless the multi-threading occurs on a single core, in which case it is only concurrent.

Parallel.js

ParallelJS  provides a great easy to useAPI for web workers with many helpers. A sample usage :

var p = new Parallel([1, 2, 3, 4, 5]);console.log(p.data)


The instance p contains a set of helper methods, for example spawn, map, reduce.
Here is a simple example of map function usage. It returns a Promise with the result. This is not the right solution for multi-threading with parallel.js but only a simple example. 

p.map(function (number) {
 return number * number;
}).then(function (data) {
 console.log(data);
});

No comments: