DirtyHairy / async-mutex

A mutex for synchronizing async workflows in Javascript
MIT License
1.14k stars 63 forks source link

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

Closed CMCDragonkai closed 2 years ago

CMCDragonkai commented 3 years ago

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

DirtyHairy commented 3 years ago

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

CMCDragonkai commented 3 years ago

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

CMCDragonkai commented 3 years ago

https://gist.github.com/CMCDragonkai/4de5c1526fc58dac259e321db8cf5331

DirtyHairy commented 3 years ago

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.

CMCDragonkai commented 2 years ago

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.

DirtyHairy commented 2 years ago

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
CMCDragonkai commented 2 years ago

I've written a write-preferring RWLock. https://gist.github.com/CMCDragonkai/4de5c1526fc58dac259e321db8cf5331

CMCDragonkai commented 2 years ago

Finished up here: https://github.com/MatrixAI/js-async-locks