Debian Codegraph @

test/lib/ansible_test/_internal/thread.py

raw
1 """Python threading tools."""
2
3 from __future__ import annotations
4
5 import collections.abc as c
6 import contextlib
7 import functools
8 import sys
9 import threading
10 import queue
11 import typing as t
12
13
14 class WrappedThread(threading.Thread):
15 """Wrapper around Thread which captures results and exceptions."""
16
17 def __init__(self, action: c.Callable[[], t.Any], name: str) -> None:
18 super().__init__()
19 self._result: queue.Queue[t.Any] = queue.Queue()
20 self.action = action
21 self.result = None
22 self.name = name
23
24 def run(self) -> None:
25 """
26 Run action and capture results or exception.
27 Do not override. Do not call directly. Executed by the start() method.
28 """
29 # We truly want to catch anything that the worker thread might do including call sys.exit.
30 # Therefore, we catch *everything* (including old-style class exceptions)
31 # noinspection PyBroadException
32 try:
33 self._result.put((self.action(), None))
34 # pylint: disable=locally-disabled, bare-except
35 except: # noqa
36 self._result.put((None, sys.exc_info()))
37
38 def wait_for_result(self) -> t.Any:
39 """Wait for thread to exit and return the result or raise an exception."""
40 result, exception = self._result.get()
41
42 if exception:
43 raise exception[1].with_traceback(exception[2])
44
45 self.result = result
46
47 return result
48
49
50 def mutex[TCallable: t.Callable[..., t.Any]](func: TCallable) -> TCallable:
51 """Enforce exclusive access on a decorated function."""
52 lock = threading.Lock()
53
54 @functools.wraps(func)
55 def wrapper(*args, **kwargs):
56 """Wrapper around `func` which uses a lock to provide exclusive access to the function."""
57 with lock:
58 return func(*args, **kwargs)
59
60 return wrapper # type: ignore[return-value] # requires https://www.python.org/dev/peps/pep-0612/ support
61
62
63 __named_lock = threading.Lock()
64 __named_locks: dict[str, threading.Lock] = {}
65
66
67 @contextlib.contextmanager
68 def named_lock(name: str) -> c.Iterator[bool]:
69 """
70 Context manager that provides named locks using threading.Lock instances.
71 Once named lock instances are created they are not deleted.
72 Returns True if this is the first instance of the named lock, otherwise False.
73 """
74 with __named_lock:
75 if lock_instance := __named_locks.get(name):
76 first = False
77 else:
78 first = True
79 lock_instance = __named_locks[name] = threading.Lock()
80
81 with lock_instance:
82 yield first