Last active
December 6, 2019 02:35
-
-
Save MingweiSamuel/2cff801134aa8e9987b5322a5e46fcb9 to your computer and use it in GitHub Desktop.
Tiny Javascript Semaphore
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
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