2020-05-19 00:03:28 -03:00
|
|
|
"""High-level support for working with threads in asyncio"""
|
|
|
|
|
|
|
|
import functools
|
2020-05-21 02:20:43 -03:00
|
|
|
import contextvars
|
2020-05-19 00:03:28 -03:00
|
|
|
|
|
|
|
from . import events
|
|
|
|
|
|
|
|
|
|
|
|
__all__ = "to_thread",
|
|
|
|
|
|
|
|
|
|
|
|
async def to_thread(func, /, *args, **kwargs):
|
|
|
|
"""Asynchronously run function *func* in a separate thread.
|
|
|
|
|
|
|
|
Any *args and **kwargs supplied for this function are directly passed
|
2021-07-31 01:36:10 -03:00
|
|
|
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
2020-05-21 02:20:43 -03:00
|
|
|
allowing context variables from the main thread to be accessed in the
|
|
|
|
separate thread.
|
2020-05-19 00:03:28 -03:00
|
|
|
|
2020-05-31 04:07:04 -03:00
|
|
|
Return a coroutine that can be awaited to get the eventual result of *func*.
|
2020-05-19 00:03:28 -03:00
|
|
|
"""
|
|
|
|
loop = events.get_running_loop()
|
2020-05-21 02:20:43 -03:00
|
|
|
ctx = contextvars.copy_context()
|
|
|
|
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
2020-05-19 00:03:28 -03:00
|
|
|
return await loop.run_in_executor(None, func_call)
|