Created
January 24, 2022 09:06
-
-
Save deliro/13d46b2e2442cd9353893d001ecf6ba1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Semaphore { | |
constructor(max = 1) { | |
if (max < 1) { max = 1; } | |
this.max = max; | |
this.count = 0; | |
this.queue = []; | |
} | |
acquire() { | |
let promise; | |
if (this.count < this.max) { | |
promise = Promise.resolve(); | |
} else { | |
promise = new Promise(resolve => { | |
this.queue.push(resolve); | |
}); | |
} | |
this.count++; | |
return promise; | |
} | |
release() { | |
if (this.queue.length > 0) { | |
const resolve = this.queue.shift(); | |
resolve(); | |
} | |
this.count--; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also a mutex