Reader-Writer Lock

1.0.9 · active · verified Fri Apr 10

The `readerwriterlock` library provides a Python 3 implementation of the three classic Reader-Writer problems. It offers different lock types (Reader priority, Writer priority, Fair priority) and is compliant with the standard Python lock interface, including support for timeouts. The current version is 1.0.9, and releases are infrequent, indicating a stable and mature library.

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `RWLockFairD` to protect a shared resource. Multiple reader threads can access the resource concurrently, while writer threads gain exclusive access. The `gen_rlock()` and `gen_wlock()` methods create context managers for acquiring and releasing read and write locks, respectively.

from readerwriterlock import rwlock
import threading
import time

# Choose a fair, downgradable lock for a balanced approach
lock = rwlock.RWLockFairD()

shared_resource = []

def reader(reader_id):
    with lock.gen_rlock():
        # Multiple readers can enter this block concurrently
        print(f"Reader {reader_id}: Reading {shared_resource}")
        time.sleep(0.1) # Simulate read operation

def writer(writer_id):
    with lock.gen_wlock():
        # Only one writer can enter this block
        old_val = list(shared_resource)
        shared_resource.append(writer_id)
        print(f"Writer {writer_id}: Wrote {writer_id}, was {old_val}, now {shared_resource}")
        time.sleep(0.2) # Simulate write operation


threads = []
for i in range(3):
    threads.append(threading.Thread(target=reader, args=(f'R{i}',)))
    threads.append(threading.Thread(target=writer, args=(f'W{i}',)))

for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"Final resource state: {shared_resource}")

view raw JSON →