run_in_executor is an asyncio event-loop method for running a synchronous callable in a thread or process executor. It returns an awaitable, so the result can be awaited directly or coordinated with asyncio.gather. section 6.3.2 section 7.2.3
The method accepts the executor and a zero-argument callable. Use functools.partial to freeze arguments before submission; this adapts functions such as count(number) or get_status_code(url). section 6.3.2 section 7.2.3
Choose the executor according to the blocking work:
- Use a process pool to parallelize CPU-bound operations, such as counting tasks or partitioned MapReduce work. section 6.3.2 section 6.4.3
- Use a thread pool to move blocking operations, such as synchronous HTTP requests, off the event-loop thread while other asynchronous code runs. section 7.2.3
- Pass None to reuse the event loop’s default ThreadPoolExecutor; set a custom default with loop.set_default_executor when needed. section 7.2.4
Run synchronous requests concurrently
async def main(): loop = asyncio.get_running_loop() urls = ['https://www.example.com' for _ in range(1000)] tasks = [loop.run_in_executor( None, functools.partial(get_status_code, url) ) for url in urls] results = await asyncio.gather(*tasks) print(results)
