blog/asyncio/index.html (view raw)
1<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta name=description content="Official Lonami's website"><meta name=viewport content="width=device-width, initial-scale=1.0, user-scalable=yes"><title> An Introduction to Asyncio | Lonami's Blog </title><link rel=stylesheet href=/style.css><body><article><nav class=sections><ul><li><a href=/>lonami's site</a><li><a href=/blog class=selected>blog</a><li><a href=/golb>golb</a></ul></nav><main><h1 class=title>An Introduction to Asyncio</h1><div class=time><p>2018-06-13<p>last updated 2020-10-03</div><h2 id=index>Index</h2><ul><li><a href=https://lonami.dev/blog/asyncio/#background>Background</a><li><a href=https://lonami.dev/blog/asyncio/#input_output>Input / Output</a><li><a href=https://lonami.dev/blog/asyncio/#diving_in>Diving In</a><li><a href=https://lonami.dev/blog/asyncio/#a_toy_example>A Toy Example</a><li><a href=https://lonami.dev/blog/asyncio/#a_real_example>A Real Example</a><li><a href=https://lonami.dev/blog/asyncio/#extra_material>Extra Material</a></ul><h2 id=background>Background</h2><p>After seeing some friends struggle with <code>asyncio</code> I decided that it could be a good idea to write a blog post using my own words to explain how I understand the world of asynchronous IO. I will focus on Python's <code>asyncio</code> module but this post should apply to any other language easily.<p>So what is <code>asyncio</code> and what makes it good? Why don't we just use the old and known threads to run several parts of the code concurrently, at the same time?<p>The first reason is that <code>asyncio</code> makes your code easier to reason about, as opposed to using threads, because the amount of ways in which your code can run grows exponentially. Let's see that with an example. Imagine you have this code:<pre><code class=language-python data-lang=python>def method():
2 line 1
3 line 2
4 line 3
5 line 4
6 line 5
7</code></pre><p>And you start two threads to run the method at the same time. What is the order in which the lines of code get executed? The answer is that you can't know! The first thread can run the entire method before the second thread even starts. Or it could be the first thread that runs after the second thread. Perhaps both run the "line 1", and then the line 2. Maybe the first thread runs lines 1 and 2, and then the second thread only runs the line 1 before the first thread finishes.<p>As you can see, any combination of the order in which the lines run is possible. If the lines modify some global shared state, that will get messy quickly.<p>Second, in Python, threads <em>won't</em> make your code faster most of the time. It will only increase the concurrency of your program (which is okay if it makes many blocking calls), allowing you to run several things at the same time.<p>If you have a lot of CPU work to do though, threads aren't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once. The operations won't run in parallel!<h2 id=input-output>Input / Output</h2><p>Before we go any further, let's first stop to talk about input and output, commonly known as "IO". There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.<p>The first one is known as "blocking IO". What this means is that, when you try performing IO, the current application thread is going to <em>block</em> until the Operative System can tell you it's done. Normally, this is not a problem, since disks are pretty fast anyway, but it can soon become a performance bottleneck. And network IO will be much slower than disk IO!<pre><code class=language-python data-lang=python>import socket
8
9# Setup a network socket and a very simple HTTP request.
10# By default, sockets are open in blocking mode.
11sock = socket.socket()
12request = b'''HEAD / HTTP/1.0\r
13Host: example.com\r
14\r
15'''
16
17# "connect" will block until a successful TCP connection
18# is made to the host "example.com" on port 80.
19sock.connect(('example.com', 80))
20
21# "sendall" will repeatedly call "send" until all the data in "request" is
22# sent to the host we just connected, which blocks until the data is sent.
23sock.sendall(request)
24
25# "recv" will try to receive up to 1024 bytes from the host, and block until
26# there is any data to receive (or empty if the host closes the connection).
27response = sock.recv(1024)
28
29# After all those blocking calls, we got out data! These are the headers from
30# making a HTTP request to example.com.
31print(response.decode())
32</code></pre><p>Blocking IO offers timeouts, so that you can get control back in your code if the operation doesn't finish. Imagine that the remote host doesn't want to reply, your code would be stuck for as long as the connection remains alive!<p>But wait, what if we make the timeout small? Very, very small? If we do that, we will never block waiting for an answer. That's how asynchronous IO works, and it's the opposite of blocking IO (you can also call it non-blocking IO if you want to).<p>How does non-blocking IO work if the IO device needs a while to answer with the data? In that case, the operative system responds with "not ready", and your application gets control back so it can do other stuff while the IO device completes your request. It works a bit like this:<pre><code><app> Hey, I would like to read 16 bytes from this file
33<OS> Okay, but the disk hasn't sent me the data yet
34<app> Alright, I will do something else then
35(a lot of computer time passes)
36<app> Do you have my 16 bytes now?
37<OS> Yes, here they are! "Hello, world !!\n"
38</code></pre><p>In reality, you can tell the OS to notify you when the data is ready, as opposed to polling (constantly asking the OS whether the data is ready yet or not), which is more efficient.<p>But either way, that's the difference between blocking and non-blocking IO, and what matters is that your application gets to run more without ever needing to wait for data to arrive, because the data will be there immediately when you ask, and if it's not yet, your app can do more things meanwhile.<h2 id=diving-in>Diving In</h2><p>Now we've seen what blocking and non-blocking IO is, and how threads make your code harder to reason about, but they give concurrency (yet not more speed). Is there any other way to achieve this concurrency that doesn't involve threads? Yes! The answer is <code>asyncio</code>.<p>So how does <code>asyncio</code> help? First we need to understand a very crucial concept before we can dive any deeper, and I'm talking about the <em>event loop</em>. What is it and why do we need it?<p>You can think of the event loop as a <em>loop</em> that will be responsible for calling your <code>async</code> functions:<p><img src=https://lonami.dev/blog/asyncio/eventloop.svg alt="The Event Loop"><p>That's silly you may think. Now not only we run our code but we also have to run some "event loop". It doesn't sound beneficial at all. What are these events? Well, they are the IO events we talked about before!<p><code>asyncio</code>'s event loop is responsible for handling those IO events, such as file is ready, data arrived, flushing is done, and so on. As we saw before, we can make these events non-blocking by setting their timeout to 0.<p>Let's say you want to read from 10 files at the same time. You will ask the OS to read data from 10 files, and at first none of the reads will be ready. But the event loop will be constantly asking the OS to know which are done, and when they are done, you will get your data.<p>This has some nice advantages. It means that, instead of waiting for a network request to send you a response or some file, instead of blocking there, the event loop can decide to run other code meanwhile. Whenever the contents are ready, they can be read, and your code can continue. Waiting for the contents to be received is done with the <code>await</code> keyword, and it tells the loop that it can run other code meanwhile:<p><img src=https://lonami.dev/blog/asyncio/awaitkwd1.svg alt="Step 1, await keyword"><p><img src=https://lonami.dev/blog/asyncio/awaitkwd2.svg alt="Step 2, await keyword"><p>Start reading the code of the event loop and follow the arrows. You can see that, in the beginning, there are no events yet, so the loop calls one of your functions. The code runs until it has to <code>await</code> for some IO operation to complete, such as sending a request over the network. The method is "paused" until an event occurs (for example, an "event" occurs when the request has been sent completely).<p>While the first method is busy, the event loop can enter the second method, and run its code until the first <code>await</code>. But it can happen that the event of the second query occurs before the request on the first method, so the event loop can re-enter the second method because it has already sent the query, but the first method isn't done sending the request yet.<p>Then, the second method <code>await</code>'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to <code>await</code> for a response, and so on. Here's an explanation with pseudo-code for this process if you prefer:<pre><code class=language-python data-lang=python>async def method(request):
39 prepare request
40 await send request
41
42 await receive request
43
44 process request
45 return result
46
47run in parallel (
48 method with request 1,
49 method with request 2,
50)
51</code></pre><p>This is what the event loop will do on the above pseudo-code:<pre><code>no events pending, can advance
52
53enter method with request 1
54 prepare request
55 await sending request
56pause method with request 1
57
58no events ready, can advance
59
60enter method with request 2
61 prepare request
62 await sending request
63pause method with request 2
64
65both requests are paused, cannot advance
66wait for events
67event for request 2 arrives (sending request completed)
68
69enter method with request 2
70 await receiving response
71pause method with request 2
72
73event for request 1 arrives (sending request completed)
74
75enter method with request 1
76 await receiving response
77pause method with request 1
78
79...and so on
80</code></pre><p>You may be wondering "okay, but threads work for me, so why should I change?". There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. This results in less pressure for the operating system. The second is that we know when it may run other methods. Those are the <code>await</code> keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready (when a event occurs telling us it's ready to be used without blocking or it has completed).<p>So far, we already have two advantages. We are only using a single thread so the cost for switching between methods is low, and we can easily reason about where our program may interleave operations.<p>Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method <a href=https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at><code>loop.call_at</code></a>, without the need for spawning another thread at all.<p>To tell the <code>asyncio</code> to run the two methods shown above, we can use <a href=https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future><code>asyncio.ensure_future</code></a>, which is a way of saying "I want the future of my method to be ensured". That is, you want to run your method in the future, whenever the loop is free to do so. This method returns a <code>Future</code> object, so if your method returns a value, you can <code>await</code> this future to retrieve its result.<p>What is a <code>Future</code>? This object represents the value of something that will be there in the future, but might not be there yet. Just like you can <code>await</code> your own <code>async def</code> functions, you can <code>await</code> these <code>Future</code>'s.<p>The <code>async def</code> functions are also called "coroutines", and Python does some magic behind the scenes to turn them into such. The coroutines can be <code>await</code>'ed, and this is what you normally do.<h2 id=a-toy-example>A Toy Example</h2><p>That's all about <code>asyncio</code>! Let's wrap up with some example code. We will create a server that replies with the text a client sends, but reversed. First, we will show what you could write with normal synchronous code, and then we will port it.<p>Here is the <strong>synchronous version</strong>:<pre><code class=language-python data-lang=python># server.py
81import socket
82
83
84def server_method():
85 # create a new server socket to listen for connections
86 server = socket.socket()
87
88 # bind to localhost:6789 for new connections
89 server.bind(('localhost', 6789))
90
91 # we will listen for one client at most
92 server.listen(1)
93
94 # *block* waiting for a new client
95 client, _ = server.accept()
96
97 # *block* waiting for some data
98 data = client.recv(1024)
99
100 # reverse the data
101 data = data[::-1]
102
103 # *block* sending the data
104 client.sendall(data)
105
106 # close client and server
107 server.close()
108 client.close()
109
110
111if __name__ == '__main__':
112 # block running the server
113 server_method()
114</code></pre><pre><code class=language-python data-lang=python># client.py
115import socket
116
117
118def client_method():
119 message = b'Hello Server!\n'
120 client = socket.socket()
121
122 # *block* trying to stabilish a connection
123 client.connect(('localhost', 6789))
124
125 # *block* trying to send the message
126 print('Sending', message)
127 client.sendall(message)
128
129 # *block* until we receive a response
130 response = client.recv(1024)
131 print('Server replied', response)
132
133 client.close()
134
135
136if __name__ == '__main__':
137 client_method()
138</code></pre><p>From what we've seen, this code will block on all the lines with a comment above them saying that they will block. This means that for running more than one client or server, or both in the same file, you will need threads. But we can do better, we can rewrite it into <code>asyncio</code>!<p>The first step is to mark all your <code>def</code>initions that may block with <code>async</code>. This marks them as coroutines, which can be <code>await</code>ed on.<p>Second, since we're using low-level sockets, we need to make use of the methods that <code>asyncio</code> provides directly. If this was a third-party library, this would be just like using their <code>async def</code>initions.<p>Here is the <strong>asynchronous version</strong>:<pre><code class=language-python data-lang=python># server.py
139import asyncio
140import socket
141
142# get the default "event loop" that we will run
143loop = asyncio.get_event_loop()
144
145
146# notice our new "async" before the definition
147async def server_method():
148 server = socket.socket()
149 server.bind(('localhost', 6789))
150 server.listen(1)
151
152 # await for a new client
153 # the event loop can run other code while we wait here!
154 client, _ = await loop.sock_accept(server)
155
156 # await for some data
157 data = await loop.sock_recv(client, 1024)
158 data = data[::-1]
159
160 # await for sending the data
161 await loop.sock_sendall(client, data)
162
163 server.close()
164 client.close()
165
166
167if __name__ == '__main__':
168 # run the loop until "server method" is complete
169 loop.run_until_complete(server_method())
170</code></pre><pre><code class=language-python data-lang=python># client.py
171import asyncio
172import socket
173
174loop = asyncio.get_event_loop()
175
176
177async def client_method():
178 message = b'Hello Server!\n'
179 client = socket.socket()
180
181 # await to stabilish a connection
182 await loop.sock_connect(client, ('localhost', 6789))
183
184 # await to send the message
185 print('Sending', message)
186 await loop.sock_sendall(client, message)
187
188 # await to receive a response
189 response = await loop.sock_recv(client, 1024)
190 print('Server replied', response)
191
192 client.close()
193
194
195if __name__ == '__main__':
196 loop.run_until_complete(client_method())
197</code></pre><p>That's it! You can place these two files separately and run, first the server, then the client. You should see output in the client.<p>The big difference here is that you can easily modify the code to run more than one server or clients at the same time. Whenever you <code>await</code> the event loop will run other of your code. It seems to "block" on the <code>await</code> parts, but remember it's actually jumping to run more code, and the event loop will get back to you whenever it can.<p>In short, you need an <code>async def</code> to <code>await</code> things, and you run them with the event loop instead of calling them directly. So this…<pre><code class=language-python data-lang=python>def main():
198 ... # some code
199
200
201if __name__ == '__main__':
202 main()
203</code></pre><p>…becomes this:<pre><code class=language-python data-lang=python>import asyncio
204
205
206async def main():
207 ... # some code
208
209
210if __name__ == '__main__':
211 asyncio.get_event_loop().run_until_complete(main)
212</code></pre><p>This is pretty much how most of your <code>async</code> scripts will start, running the main method until its completion.<h2 id=a-real-example>A Real Example</h2><p>Let's have some fun with a real library. We'll be using <a href=https://github.com/LonamiWebs/Telethon>Telethon</a> to broadcast a message to our three best friends, all at the same time, thanks to the magic of <code>asyncio</code>. We'll dive right into the code, and then I'll explain our new friend <code>asyncio.wait(...)</code>:<pre><code class=language-python data-lang=python># broadcast.py
213import asyncio
214import sys
215
216from telethon import TelegramClient
217
218# (you need your own values here, check Telethon's documentation)
219api_id = 123
220api_hash = '123abc'
221friends = [
222 '@friend1__username',
223 '@friend2__username',
224 '@bestie__username'
225]
226
227# we will have to await things, so we need an async def
228async def main(message):
229 # start is a coroutine, so we need to await it to run it
230 client = await TelegramClient('me', api_id, api_hash).start()
231
232 # wait for all three client.send_message to complete
233 await asyncio.wait([
234 client.send_message(friend, message)
235 for friend in friends
236 ])
237
238 # and close our client
239 await client.disconnect()
240
241
242if __name__ == '__main__':
243 if len(sys.argv) != 2:
244 print('You must pass the message to broadcast!')
245 quit()
246
247 message = sys.argv[1]
248 asyncio.get_event_loop().run_until_complete(main(message))
249</code></pre><p>Wait… how did that send a message to all three of my friends? The magic is done here:<pre><code class=language-python data-lang=python>[
250 client.send_message(friend, message)
251 for friend in friends
252]
253</code></pre><p>This list comprehension creates another list with three coroutines, the three <code>client.send_message(...)</code>. Then we just pass that list to <code>asyncio.wait</code>:<pre><code class=language-python data-lang=python>await asyncio.wait([...])
254</code></pre><p>This method, by default, waits for the list of coroutines to run until they've all finished. You can read more on the Python <a href=https://docs.python.org/3/library/asyncio-task.html#asyncio.wait>documentation</a>. Truly a good function to know about!<p>Now whenever you have some important news for your friends, you can simply <code>python3 broadcast.py 'I bought a car!'</code> to tell all your friends about your new car! All you need to remember is that you need to <code>await</code> on coroutines, and you will be good. <code>asyncio</code> will warn you when you forget to do so.<h2 id=extra-material>Extra Material</h2><p>If you want to understand how <code>asyncio</code> works under the hood, I recommend you to watch this hour-long talk <a href=https://youtu.be/M-UcUs7IMIM>Get to grips with asyncio in Python 3</a> by Robert Smallshire. In the video, they will explain the differences between concurrency and parallelism, along with others concepts, and how to implement your own <code>asyncio</code> "scheduler" from scratch.</main><footer><div><p>Share your thoughts, or simply come hang with me <a href=https://t.me/LonamiWebs><img src=/img/telegram.svg alt=Telegram></a> <a href=mailto:totufals@hotmail.com><img src=/img/mail.svg alt=Mail></a></div></footer></article><p class=abyss>Glaze into the abyss… Oh hi there!