r/javascript • u/ccjsml • Aug 16 '24
AskJS [AskJS] The most simplest Javascript mutex implementation in the world.
I don't think you can find a version simpler than this.
export class Mutex {
private mutex = Promise.resolve();
lock(): Promise<() => void> {
return new Promise((resolve) => {
this.mutex = this.mutex.then(() => new Promise(resolve));
});
}
}To use it, do
mutex = new Mutex();
const unlock = await mutex.lock();
try {
// do something...
} finally {
unlock();
}
1
Upvotes
1
u/[deleted] Aug 16 '24
It’s nice. I’m just wondering in what type of scenario would you envision using this? Since js is single threaded, you can’t have the same concurrent resource contention typical of multithreaded environments.
However I suppose if you hold a resource before starting an asynchronous operation, then other code can sneak in and grab that resource before the async operation is done, unless you protect it with something like this. Is that the idea?