to_thread.py 2.6 KB

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