Created
February 27, 2025 11:29
-
-
Save AimWhy/00c9096fdfcb4440223ab3b1a948d9bd to your computer and use it in GitHub Desktop.
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 SynchronizedLock { | |
| constructor() { | |
| this.lock = false; | |
| this.queue = []; | |
| } | |
| async getLock(timeout = 10000) { | |
| while (this.lock) { | |
| await new Promise((resolve) => { | |
| this.queue.push(resolve); | |
| setTimeout(() => { | |
| const index = this.queue.indexOf(resolve); | |
| if (index !== -1) { | |
| this.queue.splice(index, 1); | |
| console.warn('SynchronizedLock timeout'); | |
| resolve(); | |
| } | |
| }, timeout); | |
| }); | |
| } | |
| this.lock = true; | |
| } | |
| releaseLock() { | |
| this.lock = false; | |
| const resolve = this.queue.shift(); | |
| if (resolve) resolve(); | |
| } | |
| } | |
| const synchronizedLock = new SynchronizedLock(); | |
| export default synchronizedLock; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment