Skip to content

Instantly share code, notes, and snippets.

@mrtcode
Created February 19, 2017 09:54
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 mrtcode/9736ec709c2742cb984421f68b2a6540 to your computer and use it in GitHub Desktop.
Save mrtcode/9736ec709c2742cb984421f68b2a6540 to your computer and use it in GitHub Desktop.
var locks = {};
function lock(id, callback) {
var lock = locks[id];
if (lock) {
lock.push(callback);
} else {
locks[id] = [];
callback(unlock(id));
}
function unlock(id) {
return function () {
var lock = locks[id];
if (lock.length) {
var next = lock.shift();
process.nextTick(function () {
next(unlock(id))
});
} else {
locks[id] = undefined;
}
}
}
}
lock(1, function (unlock) {
console.log('lock1');
setTimeout(unlock, 1000);
});
lock(2, function (unlock) {
console.log('lock2');
setTimeout(unlock, 1000);
});
lock(1, function (unlock) {
console.log('lock3');
setTimeout(unlock, 1000);
});
lock(2, function (unlock) {
console.log('lock4');
setTimeout(unlock, 1000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment