Search⌘ K
AI Features

Asynchronous

Explore asynchronous programming in Python by using asyncio's event loop to manage concurrency. Understand how to structure an asynchronous service, handle client requests, and the impact of CPU-bound tasks on event loop performance. Learn how to simulate and monitor asynchronous requests and prepare for challenges in Python concurrency.

We'll cover the following...

Asynchronous

We have seen our service go through various transformations and now we'll modify our service once more to make it run on asyncio's event loop. The loop runs in a single thread and all tasks get executed by the same thread. First, let us see the changes required for the service.

class PrimeService:

    def __init__(self, server_host, server_port):
        self.server_host = server_host
        self.server_port = server_port
        self.executor = ProcessPoolExecutor()

    async def handle_client(self, reader, writer):
        global requests

        while True:
            data = (await reader.read(4096)).decode()
            nth_prime = int(data)

            prime = await asyncio.create_task(find_nth_prime(nth_prime))

            writer.write(str(prime).encode())
            await writer.drain()

            requests += 1

Note we have factored out ...