| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import ctypes |
| 4 |
import ctypes.util |
| 5 |
import os |
| 6 |
import sys |
| 7 |
import traceback |
| 8 |
from contextvars import Context |
| 9 |
from functools import partial |
| 10 |
from itertools import count |
| 11 |
from threading import Lock, Thread |
| 12 |
from typing import TYPE_CHECKING, Any, Generic, TypeVar |
| 13 |
|
| 14 |
import outcome |
| 15 |
|
| 16 |
if TYPE_CHECKING: |
| 17 |
from collections.abc import Callable |
| 18 |
|
| 19 |
RetT = TypeVar("RetT") |
| 20 |
|
| 21 |
|
| 22 |
def _to_os_thread_name(name: str) -> bytes: |
| 23 |
# ctypes handles the trailing \00 |
| 24 |
return name.encode("ascii", errors="replace")[:15] |
| 25 |
|
| 26 |
|
| 27 |
# used to construct the method used to set os thread name, or None, depending on platform. |
| 28 |
# called once on import |
| 29 |
def get_os_thread_name_func() -> Callable[[int | None, str], None] | None: |
| 30 |
def namefunc( |
| 31 |
setname: Callable[[int, bytes], int], |
| 32 |
ident: int | None, |
| 33 |
name: str, |
| 34 |
) -> None: |
| 35 |
# Thread.ident is None "if it has not been started". Unclear if that can happen |
| 36 |
# with current usage. |
| 37 |
if ident is not None: # pragma: no cover |
| 38 |
setname(ident, _to_os_thread_name(name)) |
| 39 |
|
| 40 |
# namefunc on Mac also takes an ident, even if pthread_setname_np doesn't/can't use it |
| 41 |
# so the caller don't need to care about platform. |
| 42 |
def darwin_namefunc( |
| 43 |
setname: Callable[[bytes], int], |
| 44 |
ident: int | None, |
| 45 |
name: str, |
| 46 |
) -> None: |
| 47 |
# I don't know if Mac can rename threads that hasn't been started, but default |
| 48 |
# to no to be on the safe side. |
| 49 |
if ident is not None: # pragma: no cover |
| 50 |
setname(_to_os_thread_name(name)) |
| 51 |
|
| 52 |
# find the pthread library |
| 53 |
# this will fail on windows and musl |
| 54 |
libpthread_path = ctypes.util.find_library("pthread") |
| 55 |
if not libpthread_path: |
| 56 |
# musl includes pthread functions directly in libc.so |
| 57 |
# (but note that find_library("c") does not work on musl, |
| 58 |
# see: https://github.com/python/cpython/issues/65821) |
| 59 |
# so try that library instead |
| 60 |
# if it doesn't exist, CDLL() will fail below |
| 61 |
libpthread_path = "libc.so" |
| 62 |
|
| 63 |
# Sometimes windows can find the path, but gives a permission error when |
| 64 |
# accessing it. Catching a wider exception in case of more esoteric errors. |
| 65 |
# https://github.com/python-trio/trio/issues/2688 |
| 66 |
try: |
| 67 |
libpthread = ctypes.CDLL(libpthread_path) |
| 68 |
except Exception: # pragma: no cover |
| 69 |
return None |
| 70 |
|
| 71 |
# get the setname method from it |
| 72 |
# afaik this should never fail |
| 73 |
pthread_setname_np = getattr(libpthread, "pthread_setname_np", None) |
| 74 |
if pthread_setname_np is None: # pragma: no cover |
| 75 |
return None |
| 76 |
|
| 77 |
# specify function prototype |
| 78 |
pthread_setname_np.restype = ctypes.c_int |
| 79 |
|
| 80 |
# on mac OSX pthread_setname_np does not take a thread id, |
| 81 |
# it only lets threads name themselves, which is not a problem for us. |
| 82 |
# Just need to make sure to call it correctly |
| 83 |
if sys.platform == "darwin": |
| 84 |
pthread_setname_np.argtypes = [ctypes.c_char_p] |
| 85 |
return partial(darwin_namefunc, pthread_setname_np) |
| 86 |
|
| 87 |
# otherwise assume linux parameter conventions. Should also work on *BSD |
| 88 |
pthread_setname_np.argtypes = [ctypes.c_void_p, ctypes.c_char_p] |
| 89 |
return partial(namefunc, pthread_setname_np) |
| 90 |
|
| 91 |
|
| 92 |
# construct os thread name method |
| 93 |
set_os_thread_name = get_os_thread_name_func() |
| 94 |
|
| 95 |
# The "thread cache" is a simple unbounded thread pool, i.e., it automatically |
| 96 |
# spawns as many threads as needed to handle all the requests its given. Its |
| 97 |
# only purpose is to cache worker threads so that they don't have to be |
| 98 |
# started from scratch every time we want to delegate some work to a thread. |
| 99 |
# It's expected that some higher-level code will track how many threads are in |
| 100 |
# use to avoid overwhelming the system (e.g. the limiter= argument to |
| 101 |
# trio.to_thread.run_sync). |
| 102 |
# |
| 103 |
# To maximize sharing, there's only one thread cache per process, even if you |
| 104 |
# have multiple calls to trio.run. |
| 105 |
# |
| 106 |
# Guarantees: |
| 107 |
# |
| 108 |
# It's safe to call start_thread_soon simultaneously from |
| 109 |
# multiple threads. |
| 110 |
# |
| 111 |
# Idle threads are chosen in LIFO order, i.e. we *don't* spread work evenly |
| 112 |
# over all threads. Instead we try to let some threads do most of the work |
| 113 |
# while others sit idle as much as possible. Compared to FIFO, this has better |
| 114 |
# memory cache behavior, and it makes it easier to detect when we have too |
| 115 |
# many threads, so idle ones can exit. |
| 116 |
# |
| 117 |
# This code assumes that 'dict' has the following properties: |
| 118 |
# |
| 119 |
# - __setitem__, __delitem__, and popitem are all thread-safe and atomic with |
| 120 |
# respect to each other. This is guaranteed by the GIL. |
| 121 |
# |
| 122 |
# - popitem returns the most-recently-added item (i.e., __setitem__ + popitem |
| 123 |
# give you a LIFO queue). This relies on dicts being insertion-ordered, like |
| 124 |
# they are in py36+. |
| 125 |
|
| 126 |
# How long a thread will idle waiting for new work before gives up and exits. |
| 127 |
# This value is pretty arbitrary; I don't think it matters too much. |
| 128 |
IDLE_TIMEOUT = 10 # seconds |
| 129 |
|
| 130 |
name_counter = count() |
| 131 |
|
| 132 |
|
| 133 |
class WorkerThread(Generic[RetT]): |
| 134 |
__slots__ = ("_default_name", "_job", "_thread", "_thread_cache", "_worker_lock") |
| 135 |
|
| 136 |
def __init__(self, thread_cache: ThreadCache) -> None: |
| 137 |
self._job: ( |
| 138 |
tuple[ |
| 139 |
Callable[[], RetT], |
| 140 |
Callable[[outcome.Outcome[RetT]], object], |
| 141 |
str | None, |
| 142 |
] |
| 143 |
| None |
| 144 |
) = None |
| 145 |
self._thread_cache = thread_cache |
| 146 |
# This Lock is used in an unconventional way. |
| 147 |
# |
| 148 |
# "Unlocked" means we have a pending job that's been assigned to us; |
| 149 |
# "locked" means that we don't. |
| 150 |
# |
| 151 |
# Initially we have no job, so it starts out in locked state. |
| 152 |
self._worker_lock = Lock() |
| 153 |
self._worker_lock.acquire() |
| 154 |
self._default_name = f"Trio thread {next(name_counter)}" |
| 155 |
if sys.version_info >= (3, 14): |
| 156 |
self._thread = Thread( |
| 157 |
target=self._work, |
| 158 |
name=self._default_name, |
| 159 |
daemon=True, |
| 160 |
context=Context(), |
| 161 |
) |
| 162 |
else: |
| 163 |
self._thread = Thread( |
| 164 |
target=self._work, name=self._default_name, daemon=True |
| 165 |
) |
| 166 |
|
| 167 |
if set_os_thread_name: |
| 168 |
set_os_thread_name(self._thread.ident, self._default_name) |
| 169 |
self._thread.start() |
| 170 |
|
| 171 |
def _handle_job(self) -> None: |
| 172 |
# Handle job in a separate method to ensure user-created |
| 173 |
# objects are cleaned up in a consistent manner. |
| 174 |
assert self._job is not None |
| 175 |
fn, deliver, name = self._job |
| 176 |
self._job = None |
| 177 |
|
| 178 |
# set name |
| 179 |
if name is not None: |
| 180 |
self._thread.name = name |
| 181 |
if set_os_thread_name: |
| 182 |
set_os_thread_name(self._thread.ident, name) |
| 183 |
result = outcome.capture(fn) |
| 184 |
|
| 185 |
# reset name if it was changed |
| 186 |
if name is not None: |
| 187 |
self._thread.name = self._default_name |
| 188 |
if set_os_thread_name: |
| 189 |
set_os_thread_name(self._thread.ident, self._default_name) |
| 190 |
|
| 191 |
# Without this, this thread may get rescheduled after `deliver` |
| 192 |
# and only return after the kernel gets around to it. That's an |
| 193 |
# arbitrary amount of time during which we keep anything |
| 194 |
# referred to in the function alive, like contextvars. That's |
| 195 |
# surprising! |
| 196 |
del fn |
| 197 |
|
| 198 |
# Tell the cache that we're available to be assigned a new |
| 199 |
# job. We do this *before* calling 'deliver', so that if |
| 200 |
# 'deliver' triggers a new job, it can be assigned to us |
| 201 |
# instead of spawning a new thread. |
| 202 |
self._thread_cache._idle_workers[self] = None |
| 203 |
try: |
| 204 |
deliver(result) |
| 205 |
except BaseException as e: |
| 206 |
print("Exception while delivering result of thread", file=sys.stderr) |
| 207 |
traceback.print_exception(type(e), e, e.__traceback__) |
| 208 |
|
| 209 |
def _work(self) -> None: |
| 210 |
while True: |
| 211 |
if self._worker_lock.acquire(timeout=IDLE_TIMEOUT): |
| 212 |
# We got a job |
| 213 |
self._handle_job() |
| 214 |
else: |
| 215 |
# Timeout acquiring lock, so we can probably exit. But, |
| 216 |
# there's a race condition: we might be assigned a job *just* |
| 217 |
# as we're about to exit. So we have to check. |
| 218 |
try: |
| 219 |
del self._thread_cache._idle_workers[self] |
| 220 |
except KeyError: |
| 221 |
# Someone else removed us from the idle worker queue, so |
| 222 |
# they must be in the process of assigning us a job - loop |
| 223 |
# around and wait for it. |
| 224 |
continue |
| 225 |
else: |
| 226 |
# We successfully removed ourselves from the idle |
| 227 |
# worker queue, so no more jobs are incoming; it's safe to |
| 228 |
# exit. |
| 229 |
return |
| 230 |
|
| 231 |
|
| 232 |
class ThreadCache: |
| 233 |
__slots__ = ("_idle_workers",) |
| 234 |
|
| 235 |
def __init__(self) -> None: |
| 236 |
self._idle_workers: dict[WorkerThread[Any], None] = {} # type: ignore[explicit-any] |
| 237 |
|
| 238 |
def start_thread_soon( |
| 239 |
self, |
| 240 |
fn: Callable[[], RetT], |
| 241 |
deliver: Callable[[outcome.Outcome[RetT]], object], |
| 242 |
name: str | None = None, |
| 243 |
) -> None: |
| 244 |
worker: WorkerThread[RetT] |
| 245 |
try: |
| 246 |
worker, _ = self._idle_workers.popitem() |
| 247 |
except KeyError: |
| 248 |
worker = WorkerThread(self) |
| 249 |
worker._job = (fn, deliver, name) |
| 250 |
worker._worker_lock.release() |
| 251 |
|
| 252 |
|
| 253 |
THREAD_CACHE = ThreadCache() |
| 254 |
|
| 255 |
|
| 256 |
def start_thread_soon( |
| 257 |
fn: Callable[[], RetT], |
| 258 |
deliver: Callable[[outcome.Outcome[RetT]], object], |
| 259 |
name: str | None = None, |
| 260 |
) -> None: |
| 261 |
"""Runs ``deliver(outcome.capture(fn))`` in a worker thread. |
| 262 |
|
| 263 |
Generally ``fn`` does some blocking work, and ``deliver`` delivers the |
| 264 |
result back to whoever is interested. |
| 265 |
|
| 266 |
This is a low-level, no-frills interface, very similar to using |
| 267 |
`threading.Thread` to spawn a thread directly. The main difference is |
| 268 |
that this function tries to reuse threads when possible, so it can be |
| 269 |
a bit faster than `threading.Thread`. |
| 270 |
|
| 271 |
Worker threads have the `~threading.Thread.daemon` flag set, which means |
| 272 |
that if your main thread exits, worker threads will automatically be |
| 273 |
killed. If you want to make sure that your ``fn`` runs to completion, then |
| 274 |
you should make sure that the main thread remains alive until ``deliver`` |
| 275 |
is called. |
| 276 |
|
| 277 |
It is safe to call this function simultaneously from multiple threads. |
| 278 |
|
| 279 |
Args: |
| 280 |
|
| 281 |
fn (sync function): Performs arbitrary blocking work. |
| 282 |
|
| 283 |
deliver (sync function): Takes the `outcome.Outcome` of ``fn``, and |
| 284 |
delivers it. *Must not block.* |
| 285 |
|
| 286 |
Because worker threads are cached and reused for multiple calls, neither |
| 287 |
function should mutate thread-level state, like `threading.local` objects |
| 288 |
– or if they do, they should be careful to revert their changes before |
| 289 |
returning. |
| 290 |
|
| 291 |
Note: |
| 292 |
|
| 293 |
The split between ``fn`` and ``deliver`` serves two purposes. First, |
| 294 |
it's convenient, since most callers need something like this anyway. |
| 295 |
|
| 296 |
Second, it avoids a small race condition that could cause too many |
| 297 |
threads to be spawned. Consider a program that wants to run several |
| 298 |
jobs sequentially on a thread, so the main thread submits a job, waits |
| 299 |
for it to finish, submits another job, etc. In theory, this program |
| 300 |
should only need one worker thread. But what could happen is: |
| 301 |
|
| 302 |
1. Worker thread: First job finishes, and calls ``deliver``. |
| 303 |
|
| 304 |
2. Main thread: receives notification that the job finished, and calls |
| 305 |
``start_thread_soon``. |
| 306 |
|
| 307 |
3. Main thread: sees that no worker threads are marked idle, so spawns |
| 308 |
a second worker thread. |
| 309 |
|
| 310 |
4. Original worker thread: marks itself as idle. |
| 311 |
|
| 312 |
To avoid this, threads mark themselves as idle *before* calling |
| 313 |
``deliver``. |
| 314 |
|
| 315 |
Is this potential extra thread a major problem? Maybe not, but it's |
| 316 |
easy enough to avoid, and we figure that if the user is trying to |
| 317 |
limit how many threads they're using then it's polite to respect that. |
| 318 |
|
| 319 |
""" |
| 320 |
THREAD_CACHE.start_thread_soon(fn, deliver, name) |
| 321 |
|
| 322 |
|
| 323 |
def clear_worker_threads() -> ( |
| 324 |
None |
| 325 |
): # pragma: no cover # see test_clear_thread_cache_after_fork |
| 326 |
# This is OK because the child process does not actually have any |
| 327 |
# worker threads. Additionally, while WorkerThread keeps a strong |
| 328 |
# reference and so would get affected, the only place those are |
| 329 |
# stored is here. |
| 330 |
THREAD_CACHE._idle_workers.clear() |
| 331 |
|
| 332 |
|
| 333 |
if hasattr(os, "register_at_fork"): |
| 334 |
os.register_at_fork(after_in_child=clear_worker_threads) |