Skip to content

Instantly share code, notes, and snippets.

@mary-ext
Last active September 22, 2024 09:04
Show Gist options
  • Save mary-ext/dfabbcc95d0f077efabb42cd2bcba288 to your computer and use it in GitHub Desktop.
Save mary-ext/dfabbcc95d0f077efabb42cd2bcba288 to your computer and use it in GitHub Desktop.
Promise mutex/lock implemented with the Explicit Resource Management proposal
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