Skip to content

Commit c2d3681

Browse files
committed
chore: optimize async Lock
1 parent 8e82e18 commit c2d3681

File tree

1 file changed

+29
-25
lines changed

1 file changed

+29
-25
lines changed

robotcode/utils/async_tools.py

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -458,28 +458,27 @@ async def acquire(self) -> bool:
458458
fut = create_sub_future()
459459
self._waiters.append(fut)
460460

461+
try:
461462
try:
462-
try:
463463

464-
def aaa(fut: asyncio.Future[Any]) -> None:
465-
warnings.warn(f"Lock {self} takes to long {threading.current_thread()}\n, try to cancel...")
466-
fut.cancel()
464+
def aaa(fut: asyncio.Future[Any]) -> None:
465+
warnings.warn(f"Lock {self} takes to long {threading.current_thread()}\n, try to cancel...")
466+
fut.cancel()
467467

468-
h = fut.get_loop().call_later(120, aaa, fut)
469-
try:
470-
await fut
471-
finally:
472-
h.cancel()
468+
h = fut.get_loop().call_later(120, aaa, fut)
469+
try:
470+
await fut
473471
finally:
474-
# with self._lock:
472+
h.cancel()
473+
finally:
474+
with self._lock:
475475
self._waiters.remove(fut)
476-
except asyncio.CancelledError:
477-
# with self._lock:
478-
if not self._locked:
479-
self._wake_up_first()
480-
raise
476+
except asyncio.CancelledError:
477+
if not self._locked:
478+
self._wake_up_first()
479+
raise
481480

482-
# with self._lock:
481+
with self._lock:
483482
self._locked = True
484483
self._locker = asyncio.current_task()
485484

@@ -493,18 +492,18 @@ def release(self) -> None:
493492
self._locker = None
494493
wake_up = True
495494

496-
if wake_up:
497-
self._wake_up_first()
495+
if wake_up:
496+
self._wake_up_first()
498497

499498
def _wake_up_first(self) -> None:
500499
if not self._waiters:
501500
return
502501

503-
# with self._lock:
504-
try:
505-
fut = next(iter(self._waiters))
506-
except StopIteration:
507-
return
502+
with self._lock:
503+
try:
504+
fut = next(iter(self._waiters))
505+
except StopIteration:
506+
return
508507

509508
if fut.get_loop().is_running() and not fut.get_loop().is_closed():
510509
if fut.get_loop() == asyncio.get_running_loop():
@@ -588,9 +587,14 @@ def canceled(self) -> bool:
588587

589588

590589
def get_current_future_info() -> Optional[FutureInfo]:
591-
ct = asyncio.current_task()
590+
try:
591+
ct = asyncio.current_task()
592592

593-
if ct is None:
593+
if ct is None:
594+
return None
595+
except (SystemExit, KeyboardInterrupt):
596+
raise
597+
except BaseException:
594598
return None
595599

596600
if ct not in _running_tasks:

0 commit comments

Comments
 (0)