Last active
August 29, 2015 14:03
-
-
Save mainiak/4389f086431e0749c489 to your computer and use it in GitHub Desktop.
locking in node.js
This file contains hidden or 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
#!/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(); |
This file contains hidden or 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
// 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