Asynchronous Executors

suggest change

Note: Uses the Python 3.5+ async/await syntax

asyncio supports the use of Executor objects found in concurrent.futures for scheduling tasks asynchronously. Event loops have the function run_in_executor() which takes an Executor object, a Callable, and the Callable’s parameters.

Scheduling a task for an Executor

Do time intensive stuff…

import asyncio
from concurrent.futures import ThreadPoolExecutor

def func(a, b):
    # Do time intensive stuff…
    return a + b

async def main(loop):
    executor = ThreadPoolExecutor()
    result = await loop.run_in_executor(executor, func, "Hello,", " world!")
    print(result)

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    try:
        loop.run_until_complete(main(loop))
    finally:
        loop.close()

asyncio.get_event_loop() raises RuntimeError on Python 3.14 when the thread has no current loop, so the sample creates one with new_event_loop(). It prints Hello, world!.

Each event loop also has a “default” Executor slot that can be assigned to an Executor. To assign an Executor and schedule tasks from the loop you use the set_default_executor() method.

Do time intensive stuff…

NOTE: Using None as the first parameter designates the default Executor.

import asyncio
from concurrent.futures import ThreadPoolExecutor

def func(a, b):
    # Do time intensive stuff…
    return a + b

async def main(loop):
    # Using None as the first parameter designates the default Executor.
    result = await loop.run_in_executor(None, func, "Hello,", " world!")
    print(result)

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.set_default_executor(ThreadPoolExecutor())
    try:
        loop.run_until_complete(main(loop))
    finally:
        loop.close()

There are two main types of Executor in concurrent.futures, the ThreadPoolExecutor and the ProcessPoolExecutor. The ThreadPoolExecutor contains a pool of threads which can either be manually set to a specific number of threads through the constructor or defaults to min(32, (os.process_cpu_count() or 1) + 4) on Python 3.14. Since Python 3.8 that default has been the CPU count plus 4, capped at 32, not five times the number of cores. The pool is for blocking work, such as I/O and calls that release the GIL. Pure-Python CPU-bound work still takes the GIL, so those threads do not run it in parallel. The ProcessPoolExecutor reuses a pool of worker processes (by default one per processor) instead of spawning a new process for every task. It can only take tasks and parameters that are picklable. The most common non-picklable tasks are the methods of objects. If you must schedule an object’s method as a task in an Executor you must use a ThreadPoolExecutor.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents