run_in_executor in asyncio

The run_in_executor method in asyncio is a powerful tool for integrating blocking operations with the asyncio event loop. It allows you to run a callable in a specified executor, which can be either a thread pool or a process pool. This method is particularly useful for running blocking operations in a separate thread or process, thereby preventing them from blocking the event loop.

How run_in_executor Works

When you use run_in_executor, you submit a function to an executor and it returns a Future object. This Future object is awaitable, meaning you can use it in an await statement or pass it into asyncio API functions like gather. This integration allows you to handle blocking code within the asynchronous framework of asyncio.

Example with Process Pool Executor

In the following example, we demonstrate how to use run_in_executor with a process pool executor to perform a counting operation:

Listing 6.5 Process pool executors with asyncio

import asyncio
from asyncio.events import AbstractEventLoop
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from typing import List
 
 
def count(count_to: int) -> int:
    counter = 0
    while counter < count_to:
        counter = counter + 1
    return counter
 
 
async def main():
    with ProcessPoolExecutor() as process_pool:
        loop: AbstractEventLoop = asyncio.get_running_loop()              #1
        nums = [1, 3, 5, 22, 100000000]
        calls: List[partial[int]] = [partial(count, num) for num in nums] #2
        call_coros = []
 
        for call in calls:
            call_coros.append(loop.run_in_executor(process_pool, call))
 
        results = await asyncio.gather(*call_coros)                       #3
 
        for result in results:
            print(result)
 
 
if __name__ == "__main__":
    asyncio.run(main())

In this example, we create a process pool executor and get the asyncio event loop. We then partially apply each number in nums to the count function using functools.partial. These partially applied functions are submitted to the executor using loop.run_in_executor, and we keep track of the awaitable objects in call_coros. Finally, we wait for all results to finish with asyncio.gather.

Using the Default Executor

The run_in_executor method's executor parameter can be None, in which case it uses the event loop’s default executor. The default executor is a reusable singleton executor for the entire application, defaulting to a ThreadPoolExecutor unless a custom one is set with loop.set_default_executor.

Listing 7.6 Using the default executor

import functools
import requests
import asyncio
from util import async_timed
 
 
def get_status_code(url: str) -> int:
    response = requests.get(url)
    return response.status_code
 
 
@async_timed()
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)
 
asyncio.run(main())

In this example, we simplify the code by using the default executor. By passing None as the executor, asyncio creates and caches a default thread pool executor. This executor is reused for each subsequent call to run_in_executor, making it global to the event loop. The default executor will not shut down until the event loop closes, which typically happens when the application finishes. This approach simplifies the use of threads when you want to use the default thread pool executor.