Skip to content

Instantly share code, notes, and snippets.

@ehaynes99
Last active July 28, 2022 17:30
Show Gist options
  • Save ehaynes99/381382369a2960a7816496f3570a6ec2 to your computer and use it in GitHub Desktop.
Save ehaynes99/381382369a2960a7816496f3570a6ec2 to your computer and use it in GitHub Desktop.
type Semaphore = {
acquire: () => Promise<void>;
release: () => void;
};
export const simpleSemaphore = (size: number): Semaphore => {
const waiting: (() => void)[] = [];
let available = size;
const acquire = async (): Promise<void> => {
if (--available < 0) {
await new Promise<void>((r) => waiting.unshift(r));
}
};
const release = () => {
if (available >= size) {
// this would ALWAYS be a bug in the calling code
throw new Error('lock released when no lock was held')
}
available++;
waiting.pop()?.();
};
return { acquire, release };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment