今天闲着看了一下Parallel.js。这个库暂时貌似还没有什么中文的介绍(可能暂时用的人都不多吧)。所以就只能上github找它得源码和介绍看看了。貌似它的代码也不多,以后可以深入研究一下。
先简单翻译一下介绍吧:
构造函数
Parallel(data, opts)
这个data是一个你希望操作的数组,数据会保存在内存中直到完成工作,你也可以通过.data访问。你可以对数据进行一系列的操作。不过你的值都必须要序列化成JSON
opts是可选的参数:
evalPath指定指向eval.js的路径,具体什么用暂时还没有看懂,各位有知道的可以告诉我。
maxWorkers指定最大线程数,默认值是4。
synchronous定义当webworks不支持时的操作。
官方的例子:

1 var p = new Parallel([1, 2, 3, 4, 5]); 2 3 console.log(p.data); // prints [1, 2, 3, 4, 5]
其它函数:
spawn(fn)
这个函数是用来将产生一个新的线程。
fn是一个执行在线程中的函数,这个函数可以获得现在的data并返回修正值。
官方例子:

1 var p = new Parallel('forwards'); 2 3 // Spawn a remote job (we'll see more on how to use then later) 4 p.spawn(function (data) { 5 data = data.reverse(); 6 7 console.log(data); // logs sdrawrof 8 9 return data; 10 }).then(function (data) { 11 console.log(data) // logs sdrawrof 12 });
map(fn)
这个函数用来对所有的数据都创建一个线程(应该不会超过最大规定线程数)
官方例子:

1 var p = new Parallel([0, 1, 2, 3, 4, 5, 6]), 2 log = function () { console.log(arguments); }; 3 4 // One gotcha: anonymous functions cannot be serialzed 5 // If you want to do recursion, make sure the function 6 // is named appropriately 7 function fib(n) { 8 return n < 2 ? 1 : fib(n - 1) + fib(n - 2); 9 }; 10 11 p.map(fib).then(log) 12 13 // Logs the first 7 Fibonnaci numbers, woot!
reduce(fn)
官方例子:

1 var p = new Parallel([0, 1, 2, 3, 4, 5, 6, 7, 8]); 2 3 function add(d) { return d[0] + d[1]; } 4 function factorial(n) { return n < 2 ? 1 : n * factorial(n - 1); } 5 function log() { console.log(arguments); } 6 7 p.require(factorial) 8 9 // Approximate e^10 10 p.map(function (n) { return Math.pow(10, n); }).reduce(add).then(log);
then(success, fail)
这个函数很简单,就是制定了线程执行完成以后的操作。顾名思义success就是成功时的操作,fail是失败时的操作(fail可以不提供)
官方例子:

1 var p = new Parallel([1, 2, 3]); 2 3 function dbl(n) { return n * 2; } 4 5 p.map(dbl).map(dbl).map(dbl).then(function (data) { 6 console.log(data); // logs [8, 16, 24] 7 }); 8 9 // Approximate e^10 10 p.map(function (n) { return Math.pow(10, n) / factorial(n); }).reduce(add).then(log);
require(state)
如果你有什么需要在主线程和工作线程之间分享的可以使用这个,state可以是字符串也可以是文件名。在使用这个函数的时候要注意构造函数中的可选参数evalPath一定要写上
官方例子:

1 var p = new Parallel([1, 2, 3], { evalPath: 'https://raw.github.com/adambom/parallel.js/master/lib/eval.js' }); 2 3 function cubeRoot(n) { return Math.pow(n, 1 / 3); } 4 5 // Require a function 6 p.require(cubeRoot); 7 8 // Require a file 9 p.require('blargh.js'); 10 11 p.map(function (d) { 12 return blargh(20 * cubeRoot(d)); 13 });