原有的代码是爬虫,化简完代码是这样
import asyncio
import aiohttp
async def worker():
while 1:
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.post('https://www.baidu.com') as r:
_ = await r.text()
except RuntimeError:
break
async def main():
await asyncio.wait([worker() for _ in range(100)])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
只需要不到 100 个协程,cpu 单核就可以 100%,是我对于协程有错误的理解吗,求指点