-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmutex.js
More file actions
61 lines (54 loc) · 1.57 KB
/
mutex.js
File metadata and controls
61 lines (54 loc) · 1.57 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* used for event generation */
const Events = require('events');
/* mutex class */
class Mutex
{
/* class constructor */
constructor(locked)
{
/* mutex is not locked by default */
this._locked = locked || false;
/* used for private events generation */
this._ee = new Events.EventEmitter();
/* bind methods */
this.lock = this.lock.bind(this);
this.release = this.release.bind(this);
}
/* lock semaphore for given number of accesses (or one if no
* 'count' is given) */
lock(callback)
{
/* aquire lock */
var onRelease = () => {
/* still locked? */
if (this._locked)
return;
/* drop the number of credits */
this._locked = true;
/* remove listener */
this._ee.removeListener('release', onRelease);
/* call callback */
process.nextTick(() => callback());
};
/* mutex is locked: wait for release */
if (this._locked) {
this._ee.on('release', onRelease);
/* not locked */
} else {
/* drop the number of credits */
this._locked = true;
/* call callback */
process.nextTick(() => callback());
}
}
/* release lock */
release()
{
/* simply flip the flag */
this._locked = false;
/* emit event */
process.nextTick(() => this._ee.emit('release'));
}
}
/* export class */
module.exports = Mutex;