-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcondition-variable.ts
More file actions
28 lines (24 loc) · 946 Bytes
/
condition-variable.ts
File metadata and controls
28 lines (24 loc) · 946 Bytes
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
import type { SimulationTask } from "./simulation.ts";
export class ConditionVariable {
private readonly waiters: (() => void)[] = [];
private readonly name: string;
constructor(name: string) {
this.name = name;
}
public wait(task: SimulationTask, reason: string): Promise<void> {
task.blockpoint(`condition "${this.name}" wait for "${reason}", ${this.waiters.length} other waiters`);
return new Promise((resolve) => {
this.waiters.push(async () => {
await task.checkpoint(`condition "${this.name}" woken up for "${reason}"`);
resolve();
});
});
}
public notifyAll(task: SimulationTask, reason: string): void {
task.log(`condition "${this.name}" notifying ${this.waiters.length} for "${reason}"`);
for (const resolve of this.waiters) {
resolve();
}
this.waiters.length = 0;
}
}