Format: text/x-python
⬇ Download File (2.3 KB)
   1  from __future__ import annotations
   2  
   3  import sys
   4  from collections.abc import Callable
   5  from typing import TypeVar
   6  from warnings import warn
   7  
   8  from ._core._eventloop import get_async_backend
   9  from .abc import CapacityLimiter
  10  
  11  if sys.version_info >= (3, 11):
  12      from typing import TypeVarTuple, Unpack
  13  else:
  14      from typing_extensions import TypeVarTuple, Unpack
  15  
  16  T_Retval = TypeVar("T_Retval")
  17  PosArgsT = TypeVarTuple("PosArgsT")
  18  
  19  
  20  async def run_sync(
  21      func: Callable[[Unpack[PosArgsT]], T_Retval],
  22      *args: Unpack[PosArgsT],
  23      abandon_on_cancel: bool = False,
  24      cancellable: bool | None = None,
  25      limiter: CapacityLimiter | None = None,
  26  ) -> T_Retval:
  27      """
  28      Call the given function with the given arguments in a worker thread.
  29  
  30      If the ``cancellable`` option is enabled and the task waiting for its completion is
  31      cancelled, the thread will still run its course but its return value (or any raised
  32      exception) will be ignored.
  33  
  34      :param func: a callable
  35      :param args: positional arguments for the callable
  36      :param abandon_on_cancel: ``True`` to abandon the thread (leaving it to run
  37          unchecked on own) if the host task is cancelled, ``False`` to ignore
  38          cancellations in the host task until the operation has completed in the worker
  39          thread
  40      :param cancellable: deprecated alias of ``abandon_on_cancel``; will override
  41          ``abandon_on_cancel`` if both parameters are passed
  42      :param limiter: capacity limiter to use to limit the total amount of threads running
  43          (if omitted, the default limiter is used)
  44      :return: an awaitable that yields the return value of the function.
  45  
  46      """
  47      if cancellable is not None:
  48          abandon_on_cancel = cancellable
  49          warn(
  50              "The `cancellable=` keyword argument to `anyio.to_thread.run_sync` is "
  51              "deprecated since AnyIO 4.1.0; use `abandon_on_cancel=` instead",
  52              DeprecationWarning,
  53              stacklevel=2,
  54          )
  55  
  56      return await get_async_backend().run_sync_in_worker_thread(
  57          func, args, abandon_on_cancel=abandon_on_cancel, limiter=limiter
  58      )
  59  
  60  
  61  def current_default_thread_limiter() -> CapacityLimiter:
  62      """
  63      Return the capacity limiter that is used by default to limit the number of
  64      concurrent threads.
  65  
  66      :return: a capacity limiter object
  67  
  68      """
  69      return get_async_backend().current_default_thread_limiter()
  70