Take Turns with a Mutex

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write createMutex(), returning an object with two methods, so async code can take turns with something shared, like a file being saved. acquire() returns a promise of a release function, which resolves once the lock is free: straight away if nobody holds it, otherwise when every earlier caller has had their turn, first come, first served. Calling release frees the lock for the next caller; calling the same release function again does nothing. runExclusive(task) waits for the lock, calls task (a function returning a value or a promise), releases the lock once task's promise settles, whether it resolved or rejected, and returns a promise that settles the same way task's did.

Your code must pass

  • Gives the lock straight away when it's free
  • Makes a second caller wait until release
  • Hands the lock over first come, first served
  • Doesn't let a new caller jump ahead of a waiter
  • Ignores a second call to the same release
  • runExclusive releases the lock even when the task fails