| 1 |
"""High-level support for working with threads in asyncio""" |
| 2 |
|
| 3 |
import functools |
| 4 |
import contextvars |
| 5 |
|
| 6 |
from . import events |
| 7 |
|
| 8 |
|
| 9 |
__all__ = "to_thread", |
| 10 |
|
| 11 |
|
| 12 |
async 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 |
| 16 |
to *func*. Also, the current :class:`contextvars.Context` is propagated, |
| 17 |
allowing context variables from the main thread to be accessed in the |
| 18 |
separate thread. |
| 19 |
|
| 20 |
Return a coroutine that can be awaited to get the eventual result of *func*. |
| 21 |
""" |
| 22 |
loop = events.get_running_loop() |
| 23 |
ctx = contextvars.copy_context() |
| 24 |
func_call = functools.partial(ctx.run, func, *args, **kwargs) |
| 25 |
return await loop.run_in_executor(None, func_call) |