【发布时间】:2019-03-15 18:54:03
【问题描述】:
使用这个 asyncio 代码,我的导师说所有协程(这里是 50 个“fetch_page”)首先停止在第一个 async with 并等待,然后它们都从那里恢复并停止在第二个 async with,然后最后他们都回来了。
import aiohttp
import asyncio
async def fetch_page(url):
print(1)
async with aiohttp.ClientSession() as session:
print(2)
async with session.get(url) as response:
print(3)
return response.status
loop = asyncio.get_event_loop()
tasks = [fetch_page('http://google.com') for i in range(50)]
loop.run_until_complete(asyncio.gather(*tasks))
我正在调试这个,我必须说他错了。在调试时,我看到所有协程都按顺序转到第二个async with,然后它们都停止了。然后,一旦所有 50 个协程恢复,它们就会执行 session.get(url) 并返回。
但为什么不是所有的协程都停在第一个 async with 处?
打印输出:“1 2 1 2 1 2 ... 3 3 3 ...”,而不是“1 1 1 ... 2 2 2 ... 3 3 3 ...”
【问题讨论】:
标签: python python-asyncio