Skip to content

Instantly share code, notes, and snippets.

@mainiak
Last active August 29, 2015 14:03
Show Gist options
  • Save mainiak/4389f086431e0749c489 to your computer and use it in GitHub Desktop.
Save mainiak/4389f086431e0749c489 to your computer and use it in GitHub Desktop.
locking in node.js
#!/usr/bin/env node
var Lock = require('./lock.js');
var lock1 = new Lock();
console.log('lock1.get() #1: ' + lock1.get(function () {
console.log('this will never run');
}));
console.log('lock1.get() #2: ' + lock1.get(function () {
console.log('this will run');
}));
lock1.free();
// http://www.howardism.org/Technical/JavaScript/Locks.html
function Lock() {
return((function() {
var locked = false;
var requesters = [];
function get(cb) {
if (locked) {
requesters.push(cb);
return false;
} else {
locked = true;
return true;
}
}
function free() {
var cb;
if (requesters.length == 0) {
locked = false;
}
if (requesters.length >= 1) {
cb = requesters.pop();
cb();
}
return locked;
}
return {
get: get,
free: free
}
})());
}
module.exports = Lock;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment