blob: 34b7513a42090298a69a92858e8deb91322c6bfb [file] [log] [blame]
Miss Islington (bot)e2991302020-05-19 03:03:25 -07001"""High-level support for working with threads in asyncio"""
2
3import functools
Miss Islington (bot)3e650542020-05-20 22:38:00 -07004import contextvars
Miss Islington (bot)e2991302020-05-19 03:03:25 -07005
6from . import events
7
8
9__all__ = "to_thread",
10
11
12async def to_thread(func, /, *args, **kwargs):
13 """Asynchronously run function *func* in a separate thread.
14
15 Any *args and **kwargs supplied for this function are directly passed
Miss Islington (bot)3e650542020-05-20 22:38:00 -070016 to *func*. Also, the current :class:`contextvars.Context` is propogated,
17 allowing context variables from the main thread to be accessed in the
18 separate thread.
Miss Islington (bot)e2991302020-05-19 03:03:25 -070019
Miss Islington (bot)cdb015b2020-05-31 00:26:20 -070020 Return a coroutine that can be awaited to get the eventual result of *func*.
Miss Islington (bot)e2991302020-05-19 03:03:25 -070021 """
22 loop = events.get_running_loop()
Miss Islington (bot)3e650542020-05-20 22:38:00 -070023 ctx = contextvars.copy_context()
24 func_call = functools.partial(ctx.run, func, *args, **kwargs)
Miss Islington (bot)e2991302020-05-19 03:03:25 -070025 return await loop.run_in_executor(None, func_call)