Last active
September 22, 2024 09:04
-
-
Save mary-ext/dfabbcc95d0f077efabb42cd2bcba288 to your computer and use it in GitHub Desktop.
Promise mutex/lock implemented with the Explicit Resource Management proposal
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
export const createLock = () => { | |
let promise = Promise.resolve(); | |
return { | |
async acquire(): Promise<Disposable> { | |
const { promise: next, resolve } = Promise.withResolvers<void>(); | |
const prev = promise; | |
promise = next; | |
await prev; | |
return { [Symbol.dispose]: resolve }; | |
}, | |
}; | |
}; | |
const lock = createLock(); | |
(async () => { | |
console.log(`a: acquiring`); | |
using _lck = await lock.acquire(); | |
console.log(`a: acquired`); | |
await new Promise((res) => setTimeout(res, 50)); | |
console.log(`a: releasing`); | |
})(); | |
(async () => { | |
console.log(`b: acquiring`); | |
using _lck = await lock.acquire(); | |
console.log(`b: acquired`); | |
await new Promise((res) => setTimeout(res, 50)); | |
console.log(`b: releasing`); | |
})(); | |
(async () => { | |
await new Promise((res) => setTimeout(res, 50)); | |
console.log(`c: acquiring`); | |
using _lck = await lock.acquire(); | |
console.log(`c: acquired`); | |
await new Promise((res) => setTimeout(res, 50)); | |
console.log(`c: releasing`); | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment