Skip to content

Instantly share code, notes, and snippets.

@emliunix
Created January 31, 2019 06:28
Show Gist options
  • Save emliunix/7dba4a6a525f667d4855218ffd9072cf to your computer and use it in GitHub Desktop.
Save emliunix/7dba4a6a525f667d4855218ffd9072cf to your computer and use it in GitHub Desktop.
Semaphore
class S {
constructor(n) {
this.n = n
this.waiting = []
}
acquire() {
const self = this
let p = new Promise(function (resolve, reject) {
self.waiting.push(resolve)
})
this._check()
return p
}
release() {
this.n++
this._check()
}
_check() {
while (this.n > 0 && this.waiting.length != 0) {
this.n--
this.waiting.pop()(this.n)
}
}
}
function run(s, i) {
console.log(`Working ${i}`);
setTimeout(() => s.release(), 3000)
}
(async function() {
let s = new S(3)
let i = 0
while (true) {
await s.acquire()
run(s, i++)
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment