Skip to content

Locks

ReadersWriterLock

ReadersWriterLock()

A readers-writer lock (RW lock) implementation.

This lock allows multiple readers to hold the lock simultaneously, as long as there are no writers. When a writer requests the lock, it blocks until all current readers have released it. While a writer holds the lock, no other readers or writers can acquire it.

This implementation is reentrant: a reader or writer thread that already holds the lock can acquire it again, but every acquisition must be matched by a release.

It is recommended to use a with statement to manage the lock.

Example usage

lock = ReadersWriterLock()

with lock.reader():
    # do a read

with lock.writer():
    # do a write

Warning

Readers may not become writers and vice versa. That is, the following code will block forever:

lock = ReadersWriterLock()

with lock.reader():
    with lock.writer():
        pass

Classes:

  • ReaderLock

    A lock object that provides shared access for readers.

  • WriterLock

    A lock object that provides exclusive access for writers.

Methods:

  • reader

    Return a reader lock object.

  • writer

    Return a writer lock object.

ReaderLock

ReaderLock(rw_lock: ReadersWriterLock)

A lock object that provides shared access for readers.

Methods:

__enter__

__enter__()

__exit__

__exit__(exc_type, exc_val, exc_tb)

acquire

acquire()

Acquire the reader lock.

Blocks if a writer currently holds the lock.

release

release()

Release the reader lock.

WriterLock

WriterLock(rw_lock: ReadersWriterLock)

A lock object that provides exclusive access for writers.

Methods:

__enter__

__enter__()

__exit__

__exit__(exc_type, exc_val, exc_tb)

acquire

acquire()

Acquire the writer lock.

Blocks if any readers or another writer currently hold the lock. This method is reentrant for the current writer thread.

release

release()

Release the writer lock.

reader

reader() -> ReaderLock

Return a reader lock object.

writer

writer() -> WriterLock

Return a writer lock object.