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:
- Lock write mutex
- Check read counter, lock read mutex if it is zero
- Increment read counter
- Release write mutex
- ... [do async stuff]
- Decrement read counter
- Check read counter, release read mutex if it is zero
Writer:
- Check write counter, lock write mutex if it is zero
- Increment write counter
- Lock read mutex
- ... [do async stuff]
- Release read mutex
- Decrement write counter
- Check write counter, release write mutex if it zero
I've written a write-preferring RWLock. https://gist.github.com/CMCDragonkai/4de5c1526fc58dac259e321db8cf5331
Finished up here: https://github.com/MatrixAI/js-async-locks