1 from typing import Callable, Optional, TypeVar

2 from warnings import warn

3

4 from ._core._eventloop import get_asynclib

5 from .abc import CapacityLimiter

6

7 T_Retval = TypeVar("T_Retval")

8

9

10 async def run_sync(

11 func: Callable[..., T_Retval],

12 *args: object,

13 cancellable: bool = False,

14 limiter: Optional[CapacityLimiter] = None

15) -> T_Retval:

16 """

17 Call the given function with the given arguments in a worker thread.

18

19 If the ``cancellable`` option is enabled and the task waiting for its completion is cancelled,

20 the thread will still run its course but its return value (or any raised exception) will be

21 ignored.

22

23 :param func: a callable

24 :param args: positional arguments for the callable

25 :param cancellable: ``True`` to allow cancellation of the operation

26 :param limiter: capacity limiter to use to limit the total amount of threads running

27 (if omitted, the default limiter is used)

28 :return: an awaitable that yields the return value of the function.

29

30 """

31 return await get_asynclib().run_sync_in_worker_thread(

32 func, *args, cancellable=cancellable, limiter=limiter

33 )

34

35

36 async def run_sync_in_worker_thread(

37 func: Callable[..., T_Retval],

38 *args: object,

39 cancellable: bool = False,

40 limiter: Optional[CapacityLimiter] = None

41) -> T_Retval:

42 warn(

43 "run_sync_in_worker_thread() has been deprecated, use anyio.to_thread.run_sync() instead",

44 DeprecationWarning,

45 )

46 return await run_sync(func, *args, cancellable=cancellable, limiter=limiter)

47

48

49 def current_default_thread_limiter() -> CapacityLimiter:

50 """

51 Return the capacity limiter that is used by default to limit the number of concurrent threads.

52

53 :return: a capacity limiter object

54

55 """

56 return get_asynclib().current_default_thread_limiter()

57

58

59 def current_default_worker_thread_limiter() -> CapacityLimiter:

60 warn(

61 "current_default_worker_thread_limiter() has been deprecated, "

62 "use anyio.to_thread.current_default_thread_limiter() instead",

63 DeprecationWarning,

64 )

65 return current_default_thread_limiter()