Skip to content

Instantly share code, notes, and snippets.

@julien-duponchelle
Forked from jayjanssen/semaphore.js
Created January 31, 2012 21:22
Show Gist options
  • Save julien-duponchelle/1712991 to your computer and use it in GitHub Desktop.
Save julien-duponchelle/1712991 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(i)
{
if (i == undefined) {
i = 1;
}
this.semaphore += i;
};
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