The following demonstrates using GPC API to parallelize the reduction algorithm by computing a sum in parallel (just for the illustration purpose). The image below depicts the computation flow with an assumption that the number of leaves is unknown in advance:
sum.js and click the OK button.
(function() {
var num = request.query("num");
var mtx = mutex();
var count = 0;
while( count < num ) {
// the map phase in parallel
fork("/dosum.js", count, count, 1, mtx);
count++;
}
if( count === 0 ){
response.write("0");
response.end();
return;
}
var level = 0;
while( count > 1 ) {
level++;
if( count & 1 ) {
// every level of the reduction must have an even number of nodes
fork("/dosum.js", 0, count, level, mtx);
count++;
}
count /= 2;
}
// when the reduction is complete, respond with the result
level++;
join(mtx[level][0], function(state) {
if( state.counter == 1 ) {
// returning false means this callback function must be executed again after the next task on this mutex
return false;
}
response.write(state.data);
response.end();
});
}());
dosum.js and click the OK button.function dosum(state) { sum += state.data; if( state.counter == 2 ) { // after two nodes are merged, continue to the next level index = Math.floor(index / 2); join(mtx[++level][index], dosum); } else { state.data = sum; } } sum = $args[0]; index = $args[1]; level = $args[2]; mtx = $args[3]; index = Math.floor(index / 2); join(mtx[level][index], dosum);