Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/async/barrier.mts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
The MIT License (MIT)

Copyright (c) 2024 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Copyright (c) 2025 Hans Schallmoser (hansSchall)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand All @@ -27,33 +28,38 @@ THE SOFTWARE.
---------------------------------------------------------------------------*/

export interface BarrierOptions {
paused: boolean
paused: boolean;
}

export class Barrier {
readonly #resolvers: Array<() => void> = []
#paused: boolean = true
readonly #resolvers: Array<() => void> = [];
#paused: boolean = true;
/** Creates a new barrier in the given state. The default is paused: true */
constructor(options: BarrierOptions) {
this.#paused = options.paused
this.#paused = options.paused;
}
/** Pauses this barrier causing operations to wait. */
public pause(): void {
this.#paused = true
this.#paused = true;
}
/** Resumes this barrier causing all operations to run. */
public resume(): void {
this.#paused = false
this.#dispatch()
this.#paused = false;
this.#dispatch();
}
/** Waits until this barrier enters a resumed state. */
public wait(): Promise<void> {
return this.#paused ? new Promise((resolve) => this.#resolvers.push(resolve)) : Promise.resolve(void 0)
return this.#paused ? new Promise((resolve) => this.#resolvers.push(resolve)) : Promise.resolve(void 0);
}
async #dispatch(): Promise<void> {
while (!this.#paused && this.#resolvers.length > 0) {
const resolve = this.#resolvers.shift()!
resolve()
const next = this.#resolvers.shift();
if (next) {
next();
queueMicrotask(() => {
if (!this.#paused) {
this.#dispatch();
}
});
}
}
}