Acquire a lock. This method blocks until the lock is unlocked, then sets it to locked and returns True.
(self)
| 108 | return self._locked |
| 109 | |
| 110 | async def acquire(self) -> bool: |
| 111 | """Acquire a lock. |
| 112 | |
| 113 | This method blocks until the lock is unlocked, then sets it to |
| 114 | locked and returns True. |
| 115 | """ |
| 116 | # Implement fair scheduling, where thread always waits |
| 117 | # its turn. Jumping the queue if all are cancelled is an optimization. |
| 118 | if not self._locked and ( |
| 119 | self._waiters is None or all(w.cancelled() for w in self._waiters) |
| 120 | ): |
| 121 | self._locked = True |
| 122 | return True |
| 123 | |
| 124 | if self._waiters is None: |
| 125 | self._waiters = collections.deque() |
| 126 | fut = self._get_loop().create_future() |
| 127 | self._waiters.append(fut) |
| 128 | |
| 129 | try: |
| 130 | try: |
| 131 | await fut |
| 132 | finally: |
| 133 | self._waiters.remove(fut) |
| 134 | except exceptions.CancelledError: |
| 135 | # Currently the only exception designed be able to occur here. |
| 136 | |
| 137 | # Ensure the lock invariant: If lock is not claimed (or about |
| 138 | # to be claimed by us) and there is a Task in waiters, |
| 139 | # ensure that the Task at the head will run. |
| 140 | if not self._locked: |
| 141 | self._wake_up_first() |
| 142 | raise |
| 143 | |
| 144 | # assert self._locked is False |
| 145 | self._locked = True |
| 146 | return True |
| 147 | |
| 148 | def release(self) -> None: |
| 149 | """Release a lock. |