Created
January 31, 2019 06:28
-
-
Save emliunix/7dba4a6a525f667d4855218ffd9072cf to your computer and use it in GitHub Desktop.
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
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