Created
May 27, 2011 18:30
-
-
Save jayjanssen/995860 to your computer and use it in GitHub Desktop.
Node.js semaphores
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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