blob: 34b7513a42090298a69a92858e8deb91322c6bfb [file] [log] [blame]
Kyle Stanleycc2bbc22020-05-18 23:03:28 -04001"""High-level support for working with threads in asyncio"""
2
3import functools
Kyle Stanley0f562632020-05-21 01:20:43 -04004import contextvars
Kyle Stanleycc2bbc22020-05-18 23:03:28 -04005
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
Kyle Stanley0f562632020-05-21 01:20:43 -040016 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.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -040019
Kyle Stanley2b201362020-05-31 03:07:04 -040020 Return a coroutine that can be awaited to get the eventual result of *func*.
Kyle Stanleycc2bbc22020-05-18 23:03:28 -040021 """
22 loop = events.get_running_loop()
Kyle Stanley0f562632020-05-21 01:20:43 -040023 ctx = contextvars.copy_context()
24 func_call = functools.partial(ctx.run, func, *args, **kwargs)
Kyle Stanleycc2bbc22020-05-18 23:03:28 -040025 return await loop.run_in_executor(None, func_call)