r/javascript • • 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

13 comments sorted by

10

u/[deleted] Aug 16 '24

how is this a mutex? in what way does it prevent multiple users from being able to lock the mutex at the same time?

5

u/ccjsml Aug 16 '24

JavaScript is an event-driven language where only one piece of code runs at a time until it hits a context-switching point, such as an await statement. In this implementation, multiple users must await the lock function to obtain the unlock function. As a result, they queue up in a first-in, first-out order. This ensures that only one user can hold the lock at any given time, while others wait their turn until the previous user releases the lock

1

u/eeiaao Aug 16 '24

Thanks for explanation (I wish it was in the post)

5

u/[deleted] Aug 16 '24

It doesn’t. The whole point of a mutex is that it locks mutation of a resource across multiple processes. Other processes enqueue to receive the lock when it’s available.

This doesn’t lock anything and the resource isn’t accessible to processes outside of the main thread.

2

u/TiddoLangerak Aug 16 '24

I mean, if we only understand mutexes in the context of preemptive mutlithreading, then yes, this isn't a mutex because there is no preemptive mutlithreading in JS. But if you squint even just a little bit, then you can make a very reasonable argument that JS does something akin to cooperative mutlithreading, and with that frame of mind this is a mutex.

Or even more general: if we remove the word "thread" entirely, the real purpose of a mutex is to prevent concurrent operations (or units of work) from accessing the same resource. In a preemptive multi threaded world we need to prevent concurrent threads from accessing the resource, in event-driven architectures we need to prevent concurrent coroutines from accessing the same resource.

14

u/Badashi Aug 16 '24

While I do like how elegant it is, browsers have nice implementation called Web Locks API. For node, you can install web-locks since it doesn't have a native api by itself.

Not that I dislike your implementation, I love some elegant solution like that; but I personally prefer the WebLocks API because we don't need to rely on try/catch and we can use AbortSignal if needed.

1

u/kyloxi Aug 16 '24

That's cool! Also managed to get my mind stuck for a while trying to figure out how do the callbacks work.

1

u/ccjsml Aug 16 '24

Thanks! It is beautiful isn't it.

3

u/TiddoLangerak Aug 16 '24

It's an interesting solution! Isn't it leaky though? I.e. the entire promise chain is kept for the lifetime of the mutex, so if the mutex lives long enough and is used often enough then this could cause memory issues.

4

u/[deleted] Aug 16 '24

I don’t even know what this is but it isn’t a mutex.

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?

1

u/tswaters Aug 16 '24

Don't you need. await unlock() ?

-3

u/azhder Aug 17 '24

That is not JavaScript