Skip to content

Instantly share code, notes, and snippets.

@mrk21
Created November 1, 2022 02:15
Show Gist options
  • Save mrk21/6a4c1b46b117c7c026fecebf83ca22c0 to your computer and use it in GitHub Desktop.
Save mrk21/6a4c1b46b117c7c026fecebf83ca22c0 to your computer and use it in GitHub Desktop.
Simple mutex for JavaScript
class SimpleMutex {
_lock: boolean;
_resolves: Array<() => void>;
constructor() {
this._lock = false;
this._resolves = [];
}
async synchronize(callback: () => Promise<any>) {
try {
await this.lock();
await callback();
} finally {
this.unlock();
}
}
async lock() {
if (this._lock) {
const that = this;
await new Promise<void>((resolve, _) => {
that._resolves.push(resolve);
});
} else {
this._lock = true;
}
}
unlock() {
this._lock = false;
this._resolves.forEach((resolve) => resolve());
this._resolves = [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment