这个库是否可能会阻止代码执行?
我怎么知道它是否会引起问题?
您不应该允许在任何协程中包含长时间运行的阻塞(同步)代码。这将导致阻塞您的全局事件循环,并进一步阻塞您在任何地方的所有协同路由。
async def main():
await asyncio.sleep(3) # async sleeping, it's ok
time.sleep(3) # synchronous sleeping, this freezes event loop
# and all coroutines for 3 seconds,
# you should avoid it!
await asyncio.sleep(3) # async sleeping, it's ok
如果您需要在协程内运行阻塞代码,那么应该在executor中运行(
read here
关于它)。
在编写协同路由时,应该记住这一点,但如果启用,asyncio通常会警告您此错误
debug mode
:
import asyncio
import time
async def main():
await asyncio.sleep(3)
time.sleep(3)
await asyncio.sleep(3)
loop = asyncio.get_event_loop()
loop.set_debug(True) # debug mode
try:
loop.run_until_complete(main())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
您将看到警告:
Executing <Handle <TaskWakeupMethWrapper object at 0x000002063C2521F8>(<Future finis...events.py:275>) created at C:\Users\gmn\AppData\Local\Programs\Python\Python36\Lib\asyncio\futures.py:348> took 3.000 seconds