Created
February 19, 2017 09:54
-
-
Save mrtcode/9736ec709c2742cb984421f68b2a6540 to your computer and use it in GitHub Desktop.
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 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