1. 程式人生 > 其它 >【協程】14、補充:限制併發數量Semaphore

【協程】14、補充:限制併發數量Semaphore

  • 假如你的併發達到2000個,程式會報錯:ValueError:too many file descriptors in select()。報錯的原因字面上看是Python調取的select對開啟的檔案有最大數量的限制,這個其實是作業系統的限制,Linux開啟檔案的最大數預設是1024,Windows預設是509,超過這個值,程式就開始報錯。個人推薦限制併發數的方法,設定併發數為100-500,處理速度更快。
#目標網站
url = 'https://www.baidu.com/'

#採集程式
async def hello(url,semaphore):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                return await response.read()

# 預處理函式
async def run():
    semaphore = asyncio.Semaphore(500) # 限制併發量為500
    to_get = [hello(url.format(),semaphore) for _ in range(1000)] #總共1000任務
    await asyncio.wait(to_get)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    loop.close()