Skip to content

Instantly share code, notes, and snippets.

@samermurad
Created March 22, 2023 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samermurad/1c8ad34d89279e00d1b09f8564dc8921 to your computer and use it in GitHub Desktop.
Save samermurad/1c8ad34d89279e00d1b09f8564dc8921 to your computer and use it in GitHub Desktop.
A very basic JavaScript implementation of a Mutex, using promises
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