momotor.shared.exlock

ExLock is an async reader-writer lock. Use it when many tasks may read the same data at once, but a task that changes the data needs the data to itself.

The lock has two sides:

  • The reader side can be held by many tasks at the same time, as long as no task holds the writer side.

  • The writer side can be held by one task only. No reader runs while a writer holds the lock.

ExLock extends aiorwlock.RWLock. It adds one method, get(), which returns the reader or the writer side based on a boolean. Code that receives the exclusive choice as a parameter, such as momotor.shared.state, uses this method instead of branching itself.

from momotor.shared.exlock import ExLock

lock = ExLock()

async with lock.get(exclusive=False):
    ...  # read access, shared with other readers

async with lock.get(exclusive=True):
    ...  # write access, exclusive

For a set of locks keyed by name, see momotor.shared.lockset.

API reference

class momotor.shared.exlock.ExLock(*, fast=False)

A subclass of aiorwlock.RWLock

An ExLock maintains a pair of associated locks, one for read-only operations and one for writing. The read lock may be held simultaneously by multiple reader tasks, so long as there are no writers. The write lock is exclusive.

property reader

The lock used for read, or shared, access.

The value is an instance of the private aiorwlock._ReaderLock class from aiorwlock. Use it as an async context manager, or call its acquire and release methods. Its locked property tells whether the read lock is held.

property reader_lock

Alias of reader.

property writer

The lock used for write, or exclusive, access.

The value is an instance of the private aiorwlock._WriterLock class from aiorwlock. Use it as an async context manager, or call its acquire and release methods. Its locked property tells whether the write lock is held.

property writer_lock

Alias of writer.

get(exclusive)

Get either the reader or writer lock, depending on the value of exclusive

Parameters:

exclusive (bool) – if False, requests the reader lock, otherwise the writer lock

Return type:

aiorwlock._ReaderLock | aiorwlock._WriterLock

Returns:

the requested lock