2020-05-19 11:03:28 +08:00
|
|
|
"""High-level support for working with threads in asyncio"""
|
|
|
|
|
|
|
|
import functools
|
2020-05-21 13:20:43 +08:00
|
|
|
import contextvars
|
2020-05-19 11:03:28 +08: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 12:36:10 +08:00
|
|
|
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
2020-05-21 13:20:43 +08:00
|
|
|
allowing context variables from the main thread to be accessed in the
|
|
|
|
separate thread.
|
2020-05-19 11:03:28 +08:00
|
|
|
|
2020-05-31 15:07:04 +08:00
|
|
|
Return a coroutine that can be awaited to get the eventual result of *func*.
|
2020-05-19 11:03:28 +08:00
|
|
|
"""
|
|
|
|
loop = events.get_running_loop()
|
2020-05-21 13:20:43 +08:00
|
|
|
ctx = contextvars.copy_context()
|
|
|
|
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
2020-05-19 11:03:28 +08:00
|
|
|
return await loop.run_in_executor(None, func_call)
|