Skip to content

Instantly share code, notes, and snippets.

@guileen
Created May 15, 2011 11:10
Show Gist options
  • Save guileen/973054 to your computer and use it in GitHub Desktop.
Save guileen/973054 to your computer and use it in GitHub Desktop.
nodejs parallel control flow by bitwise operation
var _a=0x01, _b=0x02, _c=0x04, _d=0x08, _e=0x10, _f=0x20, _done=0;
var triggers = [
function(){
// a,b 完成后,执行 d,execute d() when a and b done.
if(_done & (_a | _b)){
triggers.splice(triggers.indexOf(this), 1);
d(function(){
_done |= _d;
process.nextTick(trigger);
});
}
},
function(){
// b,c 完成后,执行 e,execute e() when b and c done.
if(_done & (_b | _c)){
triggers.splice(triggers.indexOf(this), 1);
e(function(){
_done |= _e;
process.nextTick(trigger);
});
}
},
function(){
// a,c 完成后,执行 f,execute f() when a and c done.
if(_done & (_a | _c)){
triggers.splice(triggers.indexOf(this), 1);
f(function(){
_done |= _f;
process.nextTick(trigger);
});
}
},
function(){
// 全部完成,all done
if(_done & (_d |_e | _f)){
triggers.splice(triggers.indexOf(this), 1);
g(function(){
console.log('end of control flow');
});
}
}
];
function trigger(){
for(var i=triggers.length -1;i>=0;i--){
triggers[i]();
}
}
a(function(){
_done |= _a;
process.nextTick(trigger);
});
b(function(){
_done |= _b;
process.nextTick(trigger);
});
c(function(){
_done |= _c;
process.nextTick(trigger);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment