Repository navigation
Expand file tree
/
Copy pathconcurrency.js
More file actions
54 lines (47 loc) · 1.42 KB
/
Copy pathconcurrency.js
File metadata and controls
54 lines (47 loc) · 1.42 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
'use strict';
// FIFO semaphore. acquire() resolves when a slot opens; release() must be
// called (preferably in a finally block) to return the slot.
// isCancelled is checked on each queue tick so cancellation is felt promptly.
class Semaphore {
constructor(limit) {
if (!Number.isInteger(limit) || limit < 1) throw new RangeError('Semaphore limit must be >= 1');
this._limit = limit;
this._active = 0;
this._queue = [];
}
acquire(isCancelled) {
if (isCancelled?.()) return Promise.reject(new Error('CANCELLED'));
return new Promise((resolve, reject) => {
const tryAcquire = () => {
if (isCancelled?.()) { reject(new Error('CANCELLED')); return; }
if (this._active < this._limit) {
this._active++;
resolve();
} else {
this._queue.push(tryAcquire);
}
};
tryAcquire();
});
}
release() {
this._active = Math.max(0, this._active - 1);
while (this._queue.length && this._active < this._limit) {
const next = this._queue.shift();
next();
}
}
// Convenience: run fn() inside an acquired slot.
async run(fn, isCancelled) {
await this.acquire(isCancelled);
try {
return await fn();
} finally {
this.release();
}
}
get active() { return this._active; }
get queued() { return this._queue.length; }
get limit() { return this._limit; }
}
module.exports = { Semaphore };