Skip to content

Instantly share code, notes, and snippets.

@cnnrrss
Last active August 6, 2023 03:42
Show Gist options
  • Save cnnrrss/3f8a3f941c7e6df0b8fd40a2e7c096e8 to your computer and use it in GitHub Desktop.
Save cnnrrss/3f8a3f941c7e6df0b8fd40a2e7c096e8 to your computer and use it in GitHub Desktop.
"""High-level support for working with threads in asyncio"""
import asyncio
import contextvars
import functools
async def run_in_thread_async(executor, func, *args, **kwargs):
"""https://github.com/python/cpython/blob/main/Lib/asyncio/threads.py"""
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context()
func_call = functools.partial(ctx.run, func, *args, **kwargs)
res = await loop.run_in_executor(executor, func_call)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment