linotp.lib.rw_lock module

Simple reader-writer locks in Python.

Python offers a number of useful synchronization primitives in the threading and Queue modules. One that is missing, however, is a simple reader-writer lock (RWLock). A RWLock allows improved concurrency over a simple mutex, and is useful for objects that have high read-to-write ratios like database caches.

Surprisingly, I haven t been able to find any implementation of these semantics, so I rolled my own in a module rwlock.py to implement a RWLock class, along with lock promotion/demotion. Hopefully it can be added to the standard library threading module. This code is hereby placed in the public domain.

Simple reader-writer locks in Python

Many readers can hold the lock XOR one and only one writer

class linotp.lib.rw_lock.RWLock

Bases: object

A simple reader-writer lock Several readers can hold the lock simultaneously, XOR one writer. Write locks have priority over reads to prevent write starvation.

acquire_read()

Acquire a read lock. Several threads can hold this typeof lock. It is exclusive with write locks.

acquire_write()

Acquire a write lock. Only one thread can hold this lock, and only when no read locks are also held.

demote()

Demote an already-acquired write lock to a read lock

promote()

Promote an already-acquired read lock to a write lock WARNING: it is very easy to deadlock with this method

release()

Release a lock, whether read or write.