Debian Codegraph @

src/trio/_core/_tests/test_thread_cache.py

raw
1 from __future__ import annotations
2
3 import os
4 import sys
5 import threading
6 import time
7 import warnings
8 from contextlib import contextmanager
9 from queue import Queue
10 from typing import TYPE_CHECKING, NoReturn
11
12 import pytest
13
14 from .. import _thread_cache
15 from .._thread_cache import ThreadCache, start_thread_soon
16 from .tutil import gc_collect_harder, slow
17
18 if TYPE_CHECKING:
19 from collections.abc import Iterator
20
21 from outcome import Outcome
22
23
24 def test_thread_cache_basics() -> None:
25 q: Queue[Outcome[object]] = Queue()
26
27 def fn() -> NoReturn:
28 raise RuntimeError("hi")
29
30 def deliver(outcome: Outcome[object]) -> None:
31 q.put(outcome)
32
33 start_thread_soon(fn, deliver)
34
35 outcome = q.get()
36 with pytest.raises(RuntimeError, match="hi"):
37 outcome.unwrap()
38
39
40 def test_thread_cache_deref() -> None:
41 res = [False]
42
43 class del_me:
44 def __call__(self) -> int:
45 return 42
46
47 def __del__(self) -> None:
48 res[0] = True
49
50 q: Queue[Outcome[int]] = Queue()
51
52 def deliver(outcome: Outcome[int]) -> None:
53 q.put(outcome)
54
55 start_thread_soon(del_me(), deliver)
56 outcome = q.get()
57 assert outcome.unwrap() == 42
58
59 gc_collect_harder()
60 assert res[0]
61
62
63 @slow
64 def test_spawning_new_thread_from_deliver_reuses_starting_thread() -> None:
65 # We know that no-one else is using the thread cache, so if we keep
66 # submitting new jobs the instant the previous one is finished, we should
67 # keep getting the same thread over and over. This tests both that the
68 # thread cache is LIFO, and that threads can be assigned new work *before*
69 # deliver exits.
70
71 # Make sure there are a few threads running, so if we weren't LIFO then we
72 # could grab the wrong one.
73 q: Queue[Outcome[object]] = Queue()
74 COUNT = 5
75 for _ in range(COUNT):
76 start_thread_soon(lambda: time.sleep(1), lambda result: q.put(result))
77 for _ in range(COUNT):
78 q.get().unwrap()
79
80 seen_threads = set()
81 done = threading.Event()
82
83 def deliver(n: int, _: object) -> None:
84 print(n)
85 seen_threads.add(threading.current_thread())
86 if n == 0:
87 done.set()
88 else:
89 start_thread_soon(lambda: None, lambda _: deliver(n - 1, _))
90
91 start_thread_soon(lambda: None, lambda _: deliver(5, _))
92
93 done.wait()
94
95 assert len(seen_threads) == 1
96
97
98 @slow
99 def test_idle_threads_exit(monkeypatch: pytest.MonkeyPatch) -> None:
100 # Temporarily set the idle timeout to something tiny, to speed up the
101 # test. (But non-zero, so that the worker loop will at least yield the
102 # CPU.)
103 monkeypatch.setattr(_thread_cache, "IDLE_TIMEOUT", 0.0001)
104
105 q: Queue[threading.Thread] = Queue()
106 start_thread_soon(lambda: None, lambda _: q.put(threading.current_thread()))
107 seen_thread = q.get()
108 # Since the idle timeout is 0, after sleeping for 1 second, the thread
109 # should have exited
110 time.sleep(1)
111 assert not seen_thread.is_alive()
112
113
114 @contextmanager
115 def _join_started_threads() -> Iterator[None]:
116 before = frozenset(threading.enumerate())
117 try:
118 yield
119 finally:
120 for thread in threading.enumerate():
121 if thread not in before:
122 thread.join(timeout=1.0)
123 assert not thread.is_alive()
124
125
126 def test_race_between_idle_exit_and_job_assignment(
127 monkeypatch: pytest.MonkeyPatch,
128 ) -> None:
129 # This is a lock where the first few times you try to acquire it with a
130 # timeout, it waits until the lock is available and then pretends to time
131 # out. Using this in our thread cache implementation causes the following
132 # sequence:
133 #
134 # 1. start_thread_soon grabs the worker thread, assigns it a job, and
135 # releases its lock.
136 # 2. The worker thread wakes up (because the lock has been released), but
137 # the JankyLock lies to it and tells it that the lock timed out. So the
138 # worker thread tries to exit.
139 # 3. The worker thread checks for the race between exiting and being
140 # assigned a job, and discovers that it *is* in the process of being
141 # assigned a job, so it loops around and tries to acquire the lock
142 # again.
143 # 4. Eventually the JankyLock admits that the lock is available, and
144 # everything proceeds as normal.
145
146 class JankyLock:
147 def __init__(self) -> None:
148 self._lock = threading.Lock()
149 self._counter = 3
150
151 def acquire(self, timeout: int = -1) -> bool:
152 got_it = self._lock.acquire(timeout=timeout)
153 if timeout == -1:
154 return True
155 elif got_it:
156 if self._counter > 0:
157 self._counter -= 1
158 self._lock.release()
159 return False
160 return True
161 else:
162 return False
163
164 def release(self) -> None:
165 self._lock.release()
166
167 monkeypatch.setattr(_thread_cache, "Lock", JankyLock)
168
169 with _join_started_threads():
170 tc = ThreadCache()
171 done = threading.Event()
172 tc.start_thread_soon(lambda: None, lambda _: done.set())
173 done.wait()
174 # Let's kill the thread we started, so it doesn't hang around until the
175 # test suite finishes. Doesn't really do any harm, but it can be confusing
176 # to see it in debug output.
177 monkeypatch.setattr(_thread_cache, "IDLE_TIMEOUT", 0.0001)
178 tc.start_thread_soon(lambda: None, lambda _: None)
179
180
181 def test_raise_in_deliver(capfd: pytest.CaptureFixture[str]) -> None:
182 seen_threads = set()
183
184 def track_threads() -> None:
185 seen_threads.add(threading.current_thread())
186
187 def deliver(_: object) -> NoReturn:
188 done.set()
189 raise RuntimeError("don't do this")
190
191 done = threading.Event()
192 start_thread_soon(track_threads, deliver)
193 done.wait()
194 done = threading.Event()
195 start_thread_soon(track_threads, lambda _: done.set())
196 done.wait()
197 assert len(seen_threads) == 1
198 err = capfd.readouterr().err
199 assert "don't do this" in err
200 assert "delivering result" in err
201
202
203 @pytest.mark.skipif(not hasattr(os, "fork"), reason="os.fork isn't supported")
204 def test_clear_thread_cache_after_fork() -> None:
205 assert hasattr(os, "fork")
206
207 def foo() -> None:
208 pass
209
210 # ensure the thread cache exists
211 done = threading.Event()
212 start_thread_soon(foo, lambda _: done.set())
213 done.wait()
214
215 with warnings.catch_warnings(record=True) as emitted:
216 # unfortunately, we can't use pytest.warns() because the child
217 # does not warn.
218 warnings.simplefilter("default")
219 child_pid = os.fork()
220
221 if child_pid != 0 and sys.version_info >= (3, 12):
222 # the warning is only emitted in the parent
223 assert len(emitted) == 1
224 assert isinstance(emitted[0].message, DeprecationWarning)
225 assert "fork() may lead to" in str(emitted[0].message)
226 else:
227 assert not emitted
228
229 # try using it
230 done = threading.Event()
231 start_thread_soon(foo, lambda _: done.set())
232 done.wait()
233
234 if child_pid != 0:
235 # if this test fails, this will hang, triggering a timeout.
236 os.waitpid(child_pid, 0)
237 else: # pragma: no cover # coverage is shut down by os._exit(0)
238 # we would *want* to allow coverage to take a snapshot here. check
239 # git blame for how to do that. however, that times out for some
240 # reason when having `tests/` in `source` for coverage.py.
241 os._exit(0)