Using the read-write lock pattern
Some use cases are biased towards read operations rather than write ones, for example in cache systems in which the number of reads over a piece of data is expected to be several orders of magnitude higher than the number of writes. In such cases the read-write lock pattern is handy because it allows concurrent reads over the shared resource and single-operation access for writing. The following example (available at Chapter 6/read_write.py) shows a simple implementation based on an enumeration to control the possible states of shared resource, and privileging write access over read access:
import asyncio
from enum import Enum
class LockState(Enum):
IDLE = 0
READING = 1
WRITING = 2
class AsyncReadWriteLock:
def init(self):
self._state = LockState.IDLE
self._reader_count = 0
self._writer_waiting = 0
self._condition = asyncio.Condition()
async def read_acquire(self):
async with self._condition...