原因:在协成中,如果有一个操作阻塞了,会影响其他的一串协成组中的其他协成,我们可以把容易产生阻塞的协成定义为可调出协成
# coding=utf-8
import asyncio
import logging
import time
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [*] %(processName)s %(threadName)s %(message)s"
)
def my_fun ():
time.sleep(4) # 模仿阻塞
return "Hello World!"
async def fetch_async (event_loop, func):
result = await event_loop.run_in_executor(None, func)
return result
if __name__ == '__main__':
logging.info("main before")
start = time.time()
# 获取异步事件循环。
event_loop = asyncio.get_event_loop()
tasks = [
fetch_async(event_loop, my_fun),
fetch_async(event_loop, my_fun)
]
try:
# 用这个协程启动循环,协程返回时这个方法将停止循环。
results = event_loop.run_until_complete(asyncio.gather(*tasks))
logging.info(results)
finally:
event_loop.close() # 当事件循环关闭以后,所有没有执行完成的协成将全部关闭
logging.info(f"main after 总用时:{time.time() - start}")
输出:
2019-10-08 19:30:16,125 [*] MainProcess MainThread main before
2019-10-08 19:30:20,135 [*] MainProcess MainThread ['Hello World!', 'Hello World!']
2019-10-08 19:30:20,135 [*] MainProcess MainThread main after 总用时:4.009721279144287