Asynchronous
This lesson demonstrates how we can convert our threaded design to an asynchronous one.
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 the methods ...