Concurrent Execution in Python with asyncio
Concurrency in Python can be achieved through various means, and one of the powerful tools available is the asyncio library. This library allows for the concurrent execution of tasks, which can be particularly useful when dealing with I/O-bound operations, such as network requests or subprocess management. Below, we explore two examples of concurrent execution using asyncio: running subprocesses concurrently and performing stress tests with concurrent web requests.
Concurrently Running Subprocesses
One of the applications of concurrency is managing multiple subprocesses simultaneously. This can be particularly useful when you need to perform operations like encryption or data processing in parallel. In the context of the book, this is demonstrated by concurrently encrypting multiple text strings using the gpg command-line application. By leveraging asyncio, you can manage these subprocesses efficiently, allowing them to run in parallel without blocking the main execution thread.
Stress Testing with Concurrent Web Requests
Another practical application of concurrency is in stress testing web applications. By sending a large number of requests to a server concurrently, you can evaluate the server's performance under load. The following example demonstrates how to implement a stress test class using asyncio and aiohttp for making HTTP requests.
Stress Test Class
The StressTest class is designed to start and stop a stress test, keeping track of the number of completed requests. It uses an asyncio event loop to manage the concurrent execution of requests. The class constructor takes a URL, the number of requests to make, and a callback function for updating progress.
Listing 7.13 The stress test class
import asyncio
from concurrent.futures import Future
from asyncio import AbstractEventLoop
from typing import Callable, Optional
from aiohttp import ClientSession
class StressTest:
def __init__(self,
loop: AbstractEventLoop,
url: str,
total_requests: int,
callback: Callable[[int, int], None]):
self._completed_requests: int = 0
self._load_test_future: Optional[Future] = None
self._loop = loop
self._url = url
self._total_requests = total_requests
self._callback = callback
self._refresh_rate = total_requests // 100
def start(self): #1
future = asyncio.run_coroutine_threadsafe(self._make_requests(), self._loop)
self._load_test_future = future
def cancel(self):
if self._load_test_future:
self._loop.call_soon_threadsafe(self._load_test_future.cancel) #2
async def _get_url(self, session: ClientSession, url: str):
try:
await session.get(url)
except Exception as e:
print(e)
self._completed_requests = self._completed_requests + 1
if self._completed_requests % self._refresh_rate == 0 \ #3
or self._completed_requests == self._total_requests:
self._callback(self._completed_requests, self._total_requests)
async def _make_requests(self):
async with ClientSession() as session:
reqs = [self._get_url(session, self._url) for _ in range(self._total_requests)]
await asyncio.gather(*reqs)
Explanation
-
Initialization: The
StressTestclass is initialized with an event loop, a target URL, the total number of requests, and a callback function. The callback is used to update a progress bar or any other UI element to reflect the progress of the test. -
Starting the Test: The
startmethod usesasyncio.run_coroutine_threadsafeto begin making requests on the event loop. The future returned by this call is stored, allowing the test to be canceled if needed. -
Making Requests: The
_make_requestscoroutine creates a list of coroutines to perform the web requests concurrently. These are passed toasyncio.gather, which runs them concurrently. -
Handling Responses: The
_get_urlcoroutine handles each request, incrementing the completed requests counter and calling the callback function when necessary to update progress.
By using asyncio for concurrent execution, both subprocess management and stress testing can be performed efficiently, leveraging Python's capabilities for handling asynchronous operations.
FAQ (Frequently asked questions)
How can subprocesses be run concurrently in Python?
What is demonstrated in Listing 13.7 of the book 'Python Concurrency with asyncio'?
What tool is used for encrypting text strings concurrently in the book 'Python Concurrency with asyncio'?