Skip to content

Instantly share code, notes, and snippets.

@jayjanssen
Created May 27, 2011 18:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jayjanssen/995860 to your computer and use it in GitHub Desktop.
Save jayjanssen/995860 to your computer and use it in GitHub Desktop.
Node.js semaphores
var Semaphore = function(callback, context) {
this.semaphore = 0;
this.callback = callback;
this.context = context || this;
};
Semaphore.prototype.increment = function() {
this.semaphore++;
};
Semaphore.prototype.execute = function() {
this.semaphore--;
if (this.semaphore <= 0 && this.callback) {
this.callback.apply(this.context, arguments); //this means that the args that actually reach the callback will be from the LAST async block to call .execute();
}
};
module.exports = Semaphore;
var Semaphore = require("semaphore"),
sys = require("sys");
var sem1 = new Semaphore(function(i) {
sys.puts("ultimate callback... iteration that executed last = " + i);
});
//create a bunch of async ops, and we only want the sys.puts() call to happen after all have finished
for (var i = 0, l = 100; i < l; i++) {
//before each async op, explicitly tell sem1 to increment internal counter
sem1.increment();
var timeout = Math.floor(Math.random()*1001); //random amount of time, up to 1 second
setTimeout((function(_i) { //close over i so we can see which iteration ends up being the last to timeout/execute
return function () { sem1.execute(_i); };
})(i), timeout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment