Skip to content

AsyncReaderWriterLock

kobi2294 edited this page Apr 22, 2019 · 1 revision

AsyncReaderWriterLock class

The AsyncReaderWriterLock class is quite similar to the AsyncMutex and the AsyncSemaphore classes except that it actually manages two types of locks. One for "readers" and one for "writers".

  • There may be any number of concurrent readers. So in a way, if you only ask for reader locks, it is as if you are not using a lock at all.
  • There may be only one concurrent writer. So writer lock is exclusive.
  • The reason you Do need to ask for reader lock is that the writer lock will no be given before all reader locks are released.

Members

  • Use the method ReaderLock to get a reader lock
  • Use the method WriterLock to get a writer lock.
  • Use the property CurrentState to query the current state of the lock. The possibilities are:
    • None: The lock is currently not locked at all, there are currently no readers or writers
    • Read: There are currently active readers, one or more
    • Write: There is currently an active writer.

Algorithm for reader lock

  • If the current state is None, or Read, you get the lock immediately.
  • If the current state is Write (so there is an active writer lock) the request is queued in the readers queue and you will get the lock later. When? read on...

Algorithm for writer lock

  • If the current state is None (no locks at all), you get the lock immediately.
  • If the current state is read or write (there are active locks - of any type) the request is queued in the writers queue and you will get the lock later. When? read on...

When a lock is released

  • If there are still active locks, then nothing happens. Which means that not queued request is handled.
  • If no active locks remain, we first check for the writers queue and the first request is served. So writers get priority.
  • If there are no waiting writer requests, then all the requests in the readers queue are served concurrently.

Some specific use cases

Scenario Result
Writer request while there are active readers Writer request is queued
Reader request while a writer lock is active Reader request is queued
Reader request while current state is Read, and a write request is pending Reader is served now. new Reader request are not queued while readers are running
Writer request while there are active writer Writer request is queued

Example

        private static List<int> _commonData = new List<int>();
        private static AsyncReaderWriterLock _lock = new AsyncReaderWriterLock();

        public async static Task<int> ReadFirstItem()
        {
            using (await _lock.ReaderLock()) {
                return _commonData.First();
            }
        }

        public async static  Task UpdateItem()
        {
            using (await _lock.WriterLock())
            {
                _commonData.Add(42);
            }
        }

Clone this wiki locally