Add a parallel operator in the async monad
This commit is contained in:
parent
6cf9614518
commit
e7efd4b524
1 changed files with 21 additions and 0 deletions
21
src/async.js
21
src/async.js
|
@ -1,6 +1,7 @@
|
|||
function Async() {
|
||||
return {
|
||||
bind: bind,
|
||||
parallel: parallel,
|
||||
run: run,
|
||||
sequence: sequence,
|
||||
wait: wait,
|
||||
|
@ -15,6 +16,26 @@ function Async() {
|
|||
}
|
||||
}
|
||||
|
||||
function parallel() {
|
||||
var threads = arguments;
|
||||
var pending = threads.length;
|
||||
var results = [];
|
||||
return function(f) {
|
||||
var useResult = function(i) {
|
||||
return function(x) {
|
||||
results[i] = x;
|
||||
pending--;
|
||||
if(pending < 1) {
|
||||
f(results);
|
||||
}
|
||||
};
|
||||
};
|
||||
for(var i = 0; i < threads.length; i++) {
|
||||
threads[i](useResult(i));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function run() {
|
||||
var m;
|
||||
if(arguments.length == 1) {
|
||||
|
|
Loading…
Reference in a new issue