Created
March 22, 2023 11:09
-
-
Save samermurad/1c8ad34d89279e00d1b09f8564dc8921 to your computer and use it in GitHub Desktop.
A very basic JavaScript implementation of a Mutex, using promises
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 Mutex { | |
constructor() { | |
this.current = Promise.resolve(); | |
} | |
async acquire() { | |
let release | |
const next = new Promise(resolve => { | |
release = () => { resolve(); }; | |
}); | |
const waiter = this.current.then(() => release); | |
this.current = next; | |
return await waiter; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment