Primitive lock objects. A primitive lock is a synchronization primitive that is not owned by a particular coroutine 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() a
| 22 | |
| 23 | |
| 24 | class Lock(_ContextManagerMixin, mixins._LoopBoundMixin): |
| 25 | """Primitive lock objects. |
| 26 | |
| 27 | A primitive lock is a synchronization primitive that is not owned |
| 28 | by a particular coroutine when locked. A primitive lock is in one |
| 29 | of two states, 'locked' or 'unlocked'. |
| 30 | |
| 31 | It is created in the unlocked state. It has two basic methods, |
| 32 | acquire() and release(). When the state is unlocked, acquire() |
| 33 | changes the state to locked and returns immediately. When the |
| 34 | state is locked, acquire() blocks until a call to release() in |
| 35 | another coroutine changes it to unlocked, then the acquire() call |
| 36 | resets it to locked and returns. The release() method should only |
| 37 | be called in the locked state; it changes the state to unlocked |
| 38 | and returns immediately. If an attempt is made to release an |
| 39 | unlocked lock, a RuntimeError will be raised. |
| 40 | |
| 41 | When more than one coroutine is blocked in acquire() waiting for |
| 42 | the state to turn to unlocked, only one coroutine proceeds when a |
| 43 | release() call resets the state to unlocked; first coroutine which |
| 44 | is blocked in acquire() is being processed. |
| 45 | |
| 46 | acquire() is a coroutine and should be called with 'await'. |
| 47 | |
| 48 | Locks also support the asynchronous context management protocol. |
| 49 | 'async with lock' statement should be used. |
| 50 | |
| 51 | Usage: |
| 52 | |
| 53 | lock = Lock() |
| 54 | ... |
| 55 | await lock.acquire() |
| 56 | try: |
| 57 | ... |
| 58 | finally: |
| 59 | lock.release() |
| 60 | |
| 61 | Context manager usage: |
| 62 | |
| 63 | lock = Lock() |
| 64 | ... |
| 65 | async with lock: |
| 66 | ... |
| 67 | |
| 68 | Lock objects can be tested for locking state: |
| 69 | |
| 70 | if not lock.locked(): |
| 71 | await lock.acquire() |
| 72 | else: |
| 73 | # lock is acquired |
| 74 | ... |
| 75 | |
| 76 | """ |
| 77 | |
| 78 | def __init__(self): |
| 79 | self._waiters = None |
| 80 | self._locked = False |
| 81 |