You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If you invoke a synchronous method within a ThreadPoolExecutor, it doesn't block the main thread.
importasynciofromconcurrent.futuresimportThreadPoolExecutorfromposit.clientimportClientasyncdefmy_async_method():
# Your asynchronous code hereprint("Async method started")
awaitasyncio.sleep(1)
print("Async method completed")
defsync_method():
# Your synchronous code hereprint("Sync method started")
client=Client()
res=client.users.get_current_user()
print(res.json())
print("Sync method completed")
asyncdefmain():
loop=asyncio.get_event_loop()
# Create a ThreadPoolExecutorexecutor=ThreadPoolExecutor()
# Run the synchronous method outside a thread pool# This blocks...sync_method()
# Run the synchronous method in the thread pool# Don't await yetfn=loop.run_in_executor(executor, sync_method)
# Run the asynchronous methodawaitmy_async_method()
awaitfnif__name__=="__main__":
asyncio.run(main())
Continuing the discussion from this thread
This comment in the fastapi project describes the problem pretty succinctly.
It sounds like calling any blocking code from an async endpoint will block the main thread.
The text was updated successfully, but these errors were encountered: