-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex.ts
More file actions
51 lines (46 loc) · 1.96 KB
/
mutex.ts
File metadata and controls
51 lines (46 loc) · 1.96 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
import { assert, defined } from "@glideapps/ts-necessities";
import type { SimulationTask } from "./simulation.ts";
export class Mutex {
/** This is `undefined` iff the mutex is unlocked. Otherwise it's an array of resolve functions, one for each waiter. */
private waiters: (() => void)[] | undefined;
private readonly name: string;
constructor(name: string) {
this.name = name;
}
public get isLocked(): boolean {
return this.waiters !== undefined;
}
public lock(task: SimulationTask, reason: string): Promise<void> {
if (this.waiters === undefined) {
task.log(`mutex "${this.name}" locked unopposed for "${reason}"`);
this.waiters = [];
return Promise.resolve();
} else {
task.blockpoint(`mutex "${this.name}" enqueue for "${reason}", ${this.waiters.length} other waiters`);
const p = new Promise<void>((resolve) => {
defined(this.waiters, "Promise init function did not run inline").push(async () => {
await task.checkpoint(
`mutex "${this.name}" acquired by waiter for "${reason}", ${defined(this.waiters).length} other waiters`,
);
resolve();
});
});
return p;
}
}
public unlock(task: SimulationTask, reason: string): void {
assert(this.waiters !== undefined, "Can't unlock a mutex that's not locked");
const resolve = this.waiters.shift();
if (resolve !== undefined) {
// Give the mutex to the first waiter
task.log(
`mutex "${this.name}" unlocked and passed to next waiter for "${reason}", ${this.waiters.length} waiters left`,
);
resolve();
} else {
// No waiters left, so unlock
task.log(`mutex "${this.name}" unlocked for "${reason}"`);
this.waiters = undefined;
}
}
}