Last active
July 28, 2022 17:30
-
-
Save ehaynes99/381382369a2960a7816496f3570a6ec2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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