版权声明: https://blog.csdn.net/u011361138/article/details/85421966
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()