Add a parallel operator in the async monad

This commit is contained in:
Tissevert 2018-12-02 00:19:52 +01:00
parent 6cf9614518
commit e7efd4b524
1 changed files with 21 additions and 0 deletions

View File

@ -1,6 +1,7 @@
function Async() { function Async() {
return { return {
bind: bind, bind: bind,
parallel: parallel,
run: run, run: run,
sequence: sequence, sequence: sequence,
wait: wait, 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() { function run() {
var m; var m;
if(arguments.length == 1) { if(arguments.length == 1) {