aiorwlock: Read Write Lock for Asyncio

1.5.1 · active · verified Fri Apr 10

aiorwlock provides a read-write lock, a synchronization primitive for `asyncio` applications. It allows multiple reader tasks to hold a lock concurrently, while a writer task obtains an exclusive lock, blocking all readers and other writers. This pattern is ideal for resources that are frequently read but infrequently written. The library is currently at version 1.5.1 and maintains an active release cadence with several minor and patch updates per year.

Warnings

Install

Imports

Quickstart

This example demonstrates basic usage of `RWLock` with multiple concurrent readers and a single writer. Readers can acquire the `reader_lock` simultaneously, but a writer acquiring the `writer_lock` will block all other readers and writers.

import asyncio
from aiorwlock import RWLock

async def reader_task(rwlock: RWLock, reader_id: int):
    print(f"Reader {reader_id}: Attempting to acquire read lock")
    async with rwlock.reader_lock:
        print(f"Reader {reader_id}: Acquired read lock")
        await asyncio.sleep(0.05) # Simulate reading
        print(f"Reader {reader_id}: Released read lock")

async def writer_task(rwlock: RWLock, writer_id: int):
    print(f"Writer {writer_id}: Attempting to acquire write lock")
    async with rwlock.writer_lock:
        print(f"Writer {writer_id}: Acquired write lock")
        await asyncio.sleep(0.1) # Simulate writing
        print(f"Writer {writer_id}: Released write lock")

async def main():
    rwlock = RWLock()
    tasks = []
    # Start some readers
    for i in range(3):
        tasks.append(asyncio.create_task(reader_task(rwlock, i)))
    # Start a writer in between
    tasks.append(asyncio.create_task(writer_task(rwlock, 100)))
    # Start more readers
    for i in range(3, 6):
        tasks.append(asyncio.create_task(reader_task(rwlock, i)))

    await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →