How do you run many async tasks concurrently with a limit?
IntermediateConceptConcurrency: threads, processes & asyncio
Answer
async def probe(client, sem, url):
async with sem:
try:
r = await client.get(url)
return url, r.status_code
except httpx.HTTPError as e:
return url, repr(e)
async def main(urls):
sem = asyncio.Semaphore(50)
async with httpx.AsyncClient(timeout=5) as client:
return await asyncio.gather(*(probe(client, sem, u) for u in urls))
Without the semaphore, 10,000 URLs means 10,000 simultaneous sockets, which hits file descriptor limits and rate limits.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?Intermediate