Skip to content

Instantly share code, notes, and snippets.

@tlrobinson
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlrobinson/12195f48dc401f14d5e1 to your computer and use it in GitHub Desktop.
Save tlrobinson/12195f48dc401f14d5e1 to your computer and use it in GitHub Desktop.
var Future = require('fibers/future');
function Lock() {
this.futures = [];
}
Lock.prototype.enter = function() {
this.futures.push(new Future);
if (this.futures.length > 1) {
this.futures[this.futures.length - 2].wait();
}
}
Lock.prototype.exit = function() {
var future = this.futures.shift();
process.nextTick(future.return.bind(future));
}
function Synchronized(func) {
var lock = new Lock;
return function() {
lock.enter();
try {
return func.apply(this, arguments);
} finally {
lock.exit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment