Created
November 1, 2022 02:15
-
-
Save mrk21/6a4c1b46b117c7c026fecebf83ca22c0 to your computer and use it in GitHub Desktop.
Simple mutex for JavaScript
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 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