bitcore-wallet-service/lib/lock.js

34 lines
538 B
JavaScript
Raw Normal View History

2015-01-27 05:18:45 -08:00
var _ = require('lodash');
var locks = {};
var Lock = function () {
2015-02-02 12:07:18 -08:00
this.taken = false;
this.queue = [];
2015-01-27 05:18:45 -08:00
};
Lock.prototype.free = function () {
2015-02-02 12:07:18 -08:00
if (this.queue.length > 0) {
var f = this.queue.shift();
f(this);
} else {
this.taken = false;
}
2015-01-27 05:18:45 -08:00
};
Lock.get = function (key, callback) {
2015-02-02 12:07:18 -08:00
if (_.isUndefined(locks[key])) {
locks[key] = new Lock();
}
var lock = locks[key];
2015-01-27 05:18:45 -08:00
2015-02-02 12:07:18 -08:00
if (lock.taken) {
lock.queue.push(callback);
} else {
lock.taken = true;
callback(lock);
}
2015-01-27 05:18:45 -08:00
};
module.exports = Lock;