Skip to content

Instantly share code, notes, and snippets.

@matanper
Created July 27, 2023 10:56
Show Gist options
  • Save matanper/ffcf4d0b0770224cb2882fd4b0994d57 to your computer and use it in GitHub Desktop.
Save matanper/ffcf4d0b0770224cb2882fd4b0994d57 to your computer and use it in GitHub Desktop.
Python blocking sync function to async function in thread decorator
def to_asyncio_in_thread(func):
async def wrapper(*args, **kwargs):
return await asyncio.get_event_loop().run_in_executor(None, lambda: func(*args, **kwargs))
return wrapper
# Usage:
@to_asyncio_in_thread
def blocking_call():
print('start wait')
sleep(10)
async def main():
await asyncio.gather(*[
asyncio.create_task(blocking_call()),
asyncio.create_task(blocking_call()),
asyncio.create_task(blocking_call())
])
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment