Skip to content

Instantly share code, notes, and snippets.

@TerrorJack

TerrorJack/sem.mjs

Created Aug 6, 2019
Embed
What would you like to do?
Async JavaScript Semaphores
function semSetPromise(sem) {
delete sem.promise;
delete sem.resolve;
sem.promise = new Promise(resolve => {
if (sem.left) {
--sem.left;
resolve();
} else {
sem.resolve = resolve;
}
});
}
function semTake(sem) {
return sem.promise.then(() => semSetPromise(sem));
}
function semPut(sem) {
++sem.left;
if (sem.resolve) {
sem.resolve();
semSetPromise(sem);
}
}
export class Sem {
static async create(n) {
const sem = new Sem();
sem.left = n;
semSetPromise(sem);
return sem;
}
take() {
return semTake(this);
}
put() {
semPut(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.