PyDocs

Nav

Networking and Interprocess Communication

Lock

asyncio

class (source) not WASI
Primitive lock objects.

A primitive lock is a synchronization primitive that is not owned
by a particular task when locked.  A primitive lock is in one
of two states, 'locked' or 'unlocked'.

It is created in the unlocked state.  It has two basic methods,
acquire() and release().  When the state is unlocked, acquire()
changes the state to locked and returns immediately.  When the
state is locked, acquire() blocks until a call to release() in
another task changes it to unlocked, then the acquire() call
resets it to locked and returns.  The release() method should only
be called in the locked state; it changes the state to unlocked
and returns immediately.  If an attempt is made to release an
unlocked lock, a RuntimeError will be raised.

When more than one task is blocked in acquire() waiting for
the state to turn to unlocked, only one task proceeds when a
release() call resets the state to unlocked; successive release()
calls will unblock tasks in FIFO order.

Locks also support the asynchronous context management protocol.
'async with lock' statement should be used.

Usage:

    lock = Lock()
    ...
    await lock.acquire()
    try:
        ...
    finally:
        lock.release()

Context manager usage:

    lock = Lock()
    ...
    async with lock:
         ...

Lock objects can be tested for locking state:

    if not lock.locked():
       await lock.acquire()
    else:
       # lock is acquired
       ...
Changed in 3.10
  • 3.10: Removed the loop parameter.
Members of Lock

a

acquire
Acquire a lock.

l

locked
Return True if lock is acquired.

r

release
Release a lock.
0 Examples
No examples for asyncio/Lock.
See Also
No see-alsos for asyncio/Lock
0 Notes
No notes for Lock