Created
July 27, 2023 10:56
-
-
Save matanper/ffcf4d0b0770224cb2882fd4b0994d57 to your computer and use it in GitHub Desktop.
Python blocking sync function to async function in thread decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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