Skip to content

Instantly share code, notes, and snippets.

@MingweiSamuel
Last active December 6, 2019 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MingweiSamuel/2cff801134aa8e9987b5322a5e46fcb9 to your computer and use it in GitHub Desktop.
Save MingweiSamuel/2cff801134aa8e9987b5322a5e46fcb9 to your computer and use it in GitHub Desktop.
Tiny Javascript Semaphore
function Semaphore(count) {
this.permits = count;
this.queue = [];
}
Semaphore.prototype.acquire = function() {
return new Promise(resolve => {
if (0 === this.permits)
this.queue.push(resolve);
else {
this.permits--;
resolve();
}
});
};
Semaphore.prototype.release = function() {
const resolve = this.queue.shift();
if (resolve)
resolve();
else
this.permits++;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment