DirtyHairy / async-mutex

A mutex for synchronizing async workflows in Javascript

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a way to implement a RWLock ontop of async-mutex?

CMCDragonkai opened this issue · comments

Seems like https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock could be done on top of async-mutex.

A RW lock is a possibility, but would most likely by a separate mutex class. Do you have a usecase in mind?

This was my attempt using async-mutex. It's read-preferring.

Sorry for my late response, life came in the way and I forgot to reply 😏 Yes, that implementation looks fine and valid. Actually, I like it better than the thought of adding it to the library. If that is fine for you I'll close the issue.

I was wondering how to do a write-preferring RWLock, the wikipedia article gives an method using condition variables, but we don't have this here.

A write-preferring one should mean that when a write call is done, it should block and queue up all the reads.

That's an interesting exercise 😏 I think the following algorithm with two mutexes and two counters should work:

Reader:

  1. Lock write mutex
  2. Check read counter, lock read mutex if it is zero
  3. Increment read counter
  4. Release write mutex
  5. ... [do async stuff]
  6. Decrement read counter
  7. Check read counter, release read mutex if it is zero

Writer:

  1. Check write counter, lock write mutex if it is zero
  2. Increment write counter
  3. Lock read mutex
  4. ... [do async stuff]
  5. Release read mutex
  6. Decrement write counter
  7. Check write counter, release write mutex if it zero