K
K
kiddle2017-11-04 21:21:04
Asynchronous programming
kiddle, 2017-11-04 21:21:04

What is a Semaphore for?

Hello, I am new to asynchronous programming. Can you please explain what Semaphore does?

async def fetch(url, session):
    async with session.get(url) as response:
        return await responce.text()

async def bound_fetch(sem, url, session):
    async with asyncio.Semaphore(1000):
        await fetch(url, session)

async def run(r):
    tasks = []
    async with ClientSession() as session:
        for i in range(10000):
            task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
            tasks.append(task)
        return await asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton_Abrosimov, 2018-12-29
@Anton_Abrosimov

Suppose you need to download 1000 pages in 10 threads.
The semaphore allows you to set a limit of 10 threads.
In other words. This is a limitation on the number of simultaneously executing tasks.
There is probably an error in the code:
return await fetch(url, session)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question