python3 異步 semaphore 信號量 控制併發

使用代碼如下

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) 得到當前運行中的任務數,來做限制,從而控制併發

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章