1. 程式人生 > >Python協程使用Semaphore訊號量同步機制限制併發量

Python協程使用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()