-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlock.js
32 lines (28 loc) · 839 Bytes
/
lock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
var Q = require('q');
var fs = require('fs');
var path = require('path');
var Lock = function(amount) {
this.amount = amount;
this.currentLock = 0;
this.delayArray = [];
};
Lock.prototype.lock = function() {
var deferred = Q.defer();
if(this.currentLock >= this.amount) {
this.delayArray.push(deferred);
} else {
fs.writeFile(path.join(__dirname, 'log', 'lock.log'), '[' + new Date().toString() + ']lock=' + this.currentLock + '\n', {flag: 'a'});
this.currentLock++;
deferred.resolve();
}
return deferred.promise;
};
Lock.prototype.unlock = function() {
if(this.delayArray.length) {
this.delayArray.shift().resolve();
} else {
fs.writeFile(path.join(__dirname, 'log', 'lock.log'), '[' + new Date().toString() + ']unlock=' + this.currentLock + '\n', {flag: 'a'});
this.currentLock--;
}
};
module.exports = Lock;