使用代码如下
from aiohttp import ClientSession
import asyncio
# 限制协程并发量
async def hello(sem, url):
async with sem:
async with ClientSession() as session:
async with session.get(f'http://localhost:8080/{url}') as response:
r = await response.read()
print(r)
await asyncio.sleep(1)
def main():
loop = asyncio.get_event_loop()
tasks = []
sem = asyncio.Semaphore(5) # this
for i in range(100000):
task = asyncio.ensure_future(hello(sem, i))
tasks.append(task)
feature = asyncio.ensure_future(asyncio.gather(*tasks))
loop.run_until_complete(feature)
if __name__ == "__main__":
main()
除此之外 还可以使用 asyncio.all_tasks(loop=loop) 得到当前运行中的任务数,来做限制,从而控制并发