UNPKG

703 BPlain TextView Raw
1export = Semaphore;
2
3
4/** A simple abstraction for limiting concurrent function calls to a specific upper bound. */
5class Semaphore {
6
7 static unlimited = new Semaphore(10000000);
8
9 constructor(private n: number) {
10 this._avail = n;
11 }
12
13 enter(fn: () => void) {
14 if (this._avail > 0) {
15 --this._avail;
16 fn();
17 } else {
18 this._queued.push(fn);
19 }
20 }
21
22 leave() {
23 if (this._queued.length > 0) {
24 var fn = this._queued.pop();
25 fn();
26 } else {
27 ++this._avail;
28 }
29 }
30
31 private _avail: number;
32 private _queued: Function[] = [];
33}