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

View all comments

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)