Table of Contents#
- Understanding the Problem: Why Non-Async Functions Block Asyncio
- Asyncio Basics: A Quick Recap
- The Solution:
asyncio.run_in_executor - Practical Examples
- Advanced Tips
- Performance Considerations
- Conclusion
- References
Understanding the Problem: Why Non-Async Functions Block Asyncio#
Synchronous functions (e.g., time.sleep, requests.get, or custom CPU-heavy logic) run sequentially and block the execution flow. In an asyncio event loop, which relies on cooperative multitasking, blocking functions grind the loop to a halt—preventing other tasks from running until the blocking operation completes.
For example, if you call a synchronous time.sleep(5) in an async function, the entire event loop will freeze for 5 seconds, blocking all other tasks.
The challenge? You may need to use such functions (e.g., legacy code, libraries without async support) but still want the benefits of concurrency. Rewriting them as async isn’t always an option—so how can we run them concurrently with asyncio without modifying the functions themselves?
Asyncio Basics: A Quick Recap#
Before diving into the solution, let’s recap a few asyncio fundamentals:
- Event Loop: The core of every asyncio application. It runs asynchronous tasks and callbacks, performs network IO operations, and handles subprocesses.
- Coroutines: Functions defined with
async defthat can pause execution atawaitstatements, allowing other tasks to run. - Tasks: Wrappers around coroutines that schedule their execution on the event loop.
- Futures: Objects representing the result of an asynchronous operation (to be completed later).
The Solution: asyncio.run_in_executor#
asyncio provides a built-in solution: loop.run_in_executor(executor, func, *args). This method runs the synchronous function func(*args) in an external executor (e.g., a thread or process pool) and returns a Future object that can be awaited.
How It Works:#
- The
executorargument specifies aconcurrent.futures.Executor(e.g.,ThreadPoolExecutororProcessPoolExecutor). IfNone,asynciouses a defaultThreadPoolExecutor. - The synchronous function runs in a separate thread/process, freeing the event loop to run other tasks while waiting.
- The
Futurereturned byrun_in_executorcan beawaited, making it compatible with async/await syntax.
Practical Examples#
Let’s walk through concrete examples to see run_in_executor in action.
Example 1: Concurrent Sleep with time.sleep#
Suppose you have a synchronous function that simulates work with time.sleep (a blocking operation). We’ll run multiple instances of this function concurrently.
Step 1: Define a Blocking Function#
First, create a simple blocking function:
import time
def blocking_task(name: str, delay: int) -> None:
"""Synchronous blocking function that simulates work with sleep."""
print(f"Task {name} starting (sleeping for {delay}s)")
time.sleep(delay) # Blocks the event loop if run directly!
print(f"Task {name} finished")Step 2: Run Sequentially (Without Concurrency)#
If we call blocking_task directly in an async function, it will block the event loop. Let’s test this:
import asyncio
async def main_sequential():
start_time = time.perf_counter()
# Run tasks sequentially (blocks event loop)
blocking_task("A", 1)
blocking_task("B", 1)
blocking_task("C", 1)
end_time = time.perf_counter()
print(f"Total time: {end_time - start_time:.2f}s")
asyncio.run(main_sequential())Output:
Task A starting (sleeping for 1s)
Task A finished
Task B starting (sleeping for 1s)
Task B finished
Task C starting (sleeping for 1s)
Task C finished
Total time: 3.01s # 1s + 1s + 1s = 3s (sequential)
Step 3: Run Concurrently with run_in_executor#
Now, use run_in_executor to run the blocking tasks in a thread pool, allowing concurrency:
async def main_concurrent():
start_time = time.perf_counter()
loop = asyncio.get_event_loop() # Get the current event loop
# Wrap blocking_task in run_in_executor for each task
task_a = loop.run_in_executor(None, blocking_task, "A", 1) # Default ThreadPool
task_b = loop.run_in_executor(None, blocking_task, "B", 1)
task_c = loop.run_in_executor(None, blocking_task, "C", 1)
# Await all tasks to complete
await asyncio.gather(task_a, task_b, task_c)
end_time = time.perf_counter()
print(f"Total time: {end_time - start_time:.2f}s")
asyncio.run(main_concurrent())Output:
Task A starting (sleeping for 1s)
Task B starting (sleeping for 1s)
Task C starting (sleeping for 1s)
Task A finished
Task B finished
Task C finished
Total time: 1.02s # ~1s (concurrent)
Key Takeaway: By offloading blocking_task to a thread pool, the event loop runs all three tasks concurrently, reducing total time from 3s to ~1s.
Example 2: Concurrent HTTP Requests with requests#
A common real-world scenario: using the synchronous requests library to fetch data from URLs. Let’s run multiple HTTP requests concurrently.
Step 1: Define a Synchronous HTTP Fetcher#
import requests
def fetch_url(url: str) -> tuple[str, int]:
"""Synchronous function to fetch a URL and return status."""
response = requests.get(url)
return (url, response.status_code)Step 2: Run Concurrently with run_in_executor#
async def main_http_concurrent():
start_time = time.perf_counter()
loop = asyncio.get_event_loop()
urls = [
"https://www.google.com",
"https://www.github.com",
"https://www.python.org",
]
# Create tasks by wrapping fetch_url in run_in_executor
tasks = [loop.run_in_executor(None, fetch_url, url) for url in urls]
# Await all tasks and collect results
results = await asyncio.gather(*tasks)
end_time = time.perf_counter()
# Print results
for url, status in results:
print(f"{url}: {status}")
print(f"Total time: {end_time - start_time:.2f}s")
asyncio.run(main_http_concurrent())Sample Output:
https://www.google.com: 200
https://www.github.com: 200
https://www.python.org: 200
Total time: 0.87s # Concurrent (vs. ~2-3s sequential)
Without run_in_executor, fetching these URLs sequentially would take ~2-3 seconds (sum of individual request times). With concurrency, it takes ~1 second (time of the slowest request).
Advanced Tips#
ThreadPoolExecutor vs. ProcessPoolExecutor#
asyncio works with two primary executor types from concurrent.futures:
| Executor | Use Case | Why? |
|---|---|---|
ThreadPoolExecutor | I/O-bound tasks (e.g., HTTP requests, file I/O) | Threads are lightweight and ideal for tasks waiting on external resources (they release the GIL). |
ProcessPoolExecutor | CPU-bound tasks (e.g., data processing) | Processes bypass the Global Interpreter Lock (GIL), allowing true parallelism for CPU-heavy work. |
When to Use ProcessPoolExecutor#
For CPU-bound tasks (e.g., mathematical computations), use ProcessPoolExecutor to avoid GIL limitations:
from concurrent.futures import ProcessPoolExecutor
def cpu_bound_task(n: int) -> int:
"""Synchronous CPU-bound task (e.g., prime number calculation)."""
return sum(i * i for i in range(n))
async def main_cpu_concurrent():
loop = asyncio.get_event_loop()
# Use ProcessPoolExecutor for CPU-bound work
with ProcessPoolExecutor() as executor:
tasks = [loop.run_in_executor(executor, cpu_bound_task, 10**7) for _ in range(4)]
results = await asyncio.gather(*tasks)
print(f"Results: {results}")
asyncio.run(main_cpu_concurrent())Custom Executors for Fine-Grained Control#
The default ThreadPoolExecutor has a max worker count of min(32, os.cpu_count() + 4). For large-scale tasks (e.g., 1000+ HTTP requests), this may cause resource exhaustion. Use a custom executor to limit workers:
from concurrent.futures import ThreadPoolExecutor
async def main_custom_executor():
loop = asyncio.get_event_loop()
# Limit to 10 workers to avoid overwhelming the system
with ThreadPoolExecutor(max_workers=10) as executor:
tasks = [loop.run_in_executor(executor, fetch_url, url) for url in large_url_list]
results = await asyncio.gather(*tasks)Handling Exceptions from Synchronous Functions#
If the synchronous function raises an exception, awaiting the Future from run_in_executor will propagate the error. Use try/except to handle it:
async def main_with_exception_handling():
loop = asyncio.get_event_loop()
try:
# Simulate a failing task (e.g., invalid URL)
result = await loop.run_in_executor(None, fetch_url, "https://invalid.url.invalid")
except requests.exceptions.ConnectionError as e:
print(f"Caught exception: {e}")
asyncio.run(main_with_exception_handling())Performance Considerations#
- Overhead: Threads/processes have overhead (memory, context switching). Avoid using
run_in_executorfor trivial tasks. - Executor Sizing: For I/O-bound tasks, use a
ThreadPoolExecutorwithmax_workersset to the number of concurrent tasks (but avoid overloading external services like APIs). - GIL Awareness: For CPU-bound tasks, always use
ProcessPoolExecutor—threads will not speed up CPU-bound work due to the GIL.
Conclusion#
asyncio.run_in_executor is a powerful tool for integrating synchronous functions into async workflows without modification. By offloading blocking tasks to thread or process pools, you can run non-async code concurrently, leveraging asyncio’s event loop for efficient I/O-bound concurrency or ProcessPoolExecutor for CPU-bound parallelism.
Whether you’re working with legacy code, third-party libraries, or simply need to bridge sync and async worlds, run_in_executor is your go-to solution.