content/blog/asyncio/index.md (view raw)
1```meta
2created: 2018-06-13
3updated: 2020-10-03
4```
5
6An Introduction to Asyncio
7==========================
8
9Index
10-----
11
12* [Background](#background)
13* [Input / Output](#input_output)
14* [Diving In](#diving_in)
15* [A Toy Example](#a_toy_example)
16* [A Real Example](#a_real_example)
17* [Extra Material](#extra_material)
18
19
20Background
21----------
22
23After seeing some friends struggle with `asyncio` 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 `asyncio` module but this post should apply to any other language easily.
24
25So what is `asyncio` 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?
26
27The first reason is that `asyncio` 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:
28
29```python
30def method():
31 line 1
32 line 2
33 line 3
34 line 4
35 line 5
36```
37
38And 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.
39
40As 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.
41
42Second, in Python, threads *won't* 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.
43
44If 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!
45
46Input / Output
47--------------
48
49Before 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.
50
51The first one is known as "blocking IO". What this means is that, when you try performing IO, the current application thread is going to *block* 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!
52
53```python
54import socket
55
56# Setup a network socket and a very simple HTTP request.
57# By default, sockets are open in blocking mode.
58sock = socket.socket()
59request = b'''HEAD / HTTP/1.0\r
60Host: example.com\r
61\r
62'''
63
64# "connect" will block until a successful TCP connection
65# is made to the host "example.com" on port 80.
66sock.connect(('example.com', 80))
67
68# "sendall" will repeatedly call "send" until all the data in "request" is
69# sent to the host we just connected, which blocks until the data is sent.
70sock.sendall(request)
71
72# "recv" will try to receive up to 1024 bytes from the host, and block until
73# there is any data to receive (or empty if the host closes the connection).
74response = sock.recv(1024)
75
76# After all those blocking calls, we got out data! These are the headers from
77# making a HTTP request to example.com.
78print(response.decode())
79```
80
81Blocking 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!
82
83But 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).
84
85How 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:
86
87```
88<app> Hey, I would like to read 16 bytes from this file
89<OS> Okay, but the disk hasn't sent me the data yet
90<app> Alright, I will do something else then
91(a lot of computer time passes)
92<app> Do you have my 16 bytes now?
93<OS> Yes, here they are! "Hello, world !!\n"
94```
95
96In 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.
97
98But 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.
99
100
101Diving In
102---------
103
104Now 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 `asyncio`.
105
106So how does `asyncio` help? First we need to understand a very crucial concept before we can dive any deeper, and I'm talking about the *event loop*. What is it and why do we need it?
107
108You can think of the event loop as a *loop* that will be responsible for calling your `async` functions:
109
110![The Event Loop](eventloop.svg)
111
112That'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!
113
114`asyncio`'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.
115
116Let'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.
117
118This 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 `await` keyword, and it tells the loop that it can run other code meanwhile:
119
120![Step 1, await keyword](awaitkwd1.svg)
121
122![Step 2, await keyword](awaitkwd2.svg)
123
124Start 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 `await` 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).
125
126While the first method is busy, the event loop can enter the second method, and run its code until the first `await`. 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.
127
128Then, the second method `await`'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 `await` for a response, and so on. Here's an explanation with pseudo-code for this process if you prefer:
129
130```python
131async def method(request):
132 prepare request
133 await send request
134
135 await receive request
136
137 process request
138 return result
139
140run in parallel (
141 method with request 1,
142 method with request 2,
143)
144```
145
146This is what the event loop will do on the above pseudo-code:
147
148```
149no events pending, can advance
150
151enter method with request 1
152 prepare request
153 await sending request
154pause method with request 1
155
156no events ready, can advance
157
158enter method with request 2
159 prepare request
160 await sending request
161pause method with request 2
162
163both requests are paused, cannot advance
164wait for events
165event for request 2 arrives (sending request completed)
166
167enter method with request 2
168 await receiving response
169pause method with request 2
170
171event for request 1 arrives (sending request completed)
172
173enter method with request 1
174 await receiving response
175pause method with request 1
176
177...and so on
178```
179
180You 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 `await` 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).
181
182So 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.
183
184Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method [`loop.call_at`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at), without the need for spawning another thread at all.
185
186To tell the `asyncio` to run the two methods shown above, we can use [`asyncio.ensure_future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future), 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 `Future` object, so if your method returns a value, you can `await` this future to retrieve its result.
187
188What is a `Future`? This object represents the value of something that will be there in the future, but might not be there yet. Just like you can `await` your own `async def` functions, you can `await` these `Future`'s.
189
190The `async def` functions are also called "coroutines", and Python does some magic behind the scenes to turn them into such. The coroutines can be `await`'ed, and this is what you normally do.
191
192
193A Toy Example
194-------------
195
196That's all about `asyncio`! 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.
197
198Here is the **synchronous version**:
199
200```python
201# server.py
202import socket
203
204
205def server_method():
206 # create a new server socket to listen for connections
207 server = socket.socket()
208
209 # bind to localhost:6789 for new connections
210 server.bind(('localhost', 6789))
211
212 # we will listen for one client at most
213 server.listen(1)
214
215 # *block* waiting for a new client
216 client, _ = server.accept()
217
218 # *block* waiting for some data
219 data = client.recv(1024)
220
221 # reverse the data
222 data = data[::-1]
223
224 # *block* sending the data
225 client.sendall(data)
226
227 # close client and server
228 server.close()
229 client.close()
230
231
232if __name__ == '__main__':
233 # block running the server
234 server_method()
235```
236
237```python
238# client.py
239import socket
240
241
242def client_method():
243 message = b'Hello Server!\n'
244 client = socket.socket()
245
246 # *block* trying to stabilish a connection
247 client.connect(('localhost', 6789))
248
249 # *block* trying to send the message
250 print('Sending', message)
251 client.sendall(message)
252
253 # *block* until we receive a response
254 response = client.recv(1024)
255 print('Server replied', response)
256
257 client.close()
258
259
260if __name__ == '__main__':
261 client_method()
262```
263
264From 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 `asyncio`!
265
266The first step is to mark all your `def`initions that may block with `async`. This marks them as coroutines, which can be `await`ed on.
267
268Second, since we're using low-level sockets, we need to make use of the methods that `asyncio` provides directly. If this was a third-party library, this would be just like using their `async def`initions.
269
270Here is the **asynchronous version**:
271
272```python
273# server.py
274import asyncio
275import socket
276
277# get the default "event loop" that we will run
278loop = asyncio.get_event_loop()
279
280
281# notice our new "async" before the definition
282async def server_method():
283 server = socket.socket()
284 server.bind(('localhost', 6789))
285 server.listen(1)
286
287 # await for a new client
288 # the event loop can run other code while we wait here!
289 client, _ = await loop.sock_accept(server)
290
291 # await for some data
292 data = await loop.sock_recv(client, 1024)
293 data = data[::-1]
294
295 # await for sending the data
296 await loop.sock_sendall(client, data)
297
298 server.close()
299 client.close()
300
301
302if __name__ == '__main__':
303 # run the loop until "server method" is complete
304 loop.run_until_complete(server_method())
305```
306
307```python
308# client.py
309import asyncio
310import socket
311
312loop = asyncio.get_event_loop()
313
314
315async def client_method():
316 message = b'Hello Server!\n'
317 client = socket.socket()
318
319 # await to stabilish a connection
320 await loop.sock_connect(client, ('localhost', 6789))
321
322 # await to send the message
323 print('Sending', message)
324 await loop.sock_sendall(client, message)
325
326 # await to receive a response
327 response = await loop.sock_recv(client, 1024)
328 print('Server replied', response)
329
330 client.close()
331
332
333if __name__ == '__main__':
334 loop.run_until_complete(client_method())
335```
336
337That's it! You can place these two files separately and run, first the server, then the client. You should see output in the client.
338
339The 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 `await` the event loop will run other of your code. It seems to "block" on the `await` parts, but remember it's actually jumping to run more code, and the event loop will get back to you whenever it can.
340
341In short, you need an `async def` to `await` things, and you run them with the event loop instead of calling them directly. So this…
342
343```python
344def main():
345 ... # some code
346
347
348if __name__ == '__main__':
349 main()
350```
351
352…becomes this:
353
354```python
355import asyncio
356
357
358async def main():
359 ... # some code
360
361
362if __name__ == '__main__':
363 asyncio.get_event_loop().run_until_complete(main)
364```
365
366This is pretty much how most of your `async` scripts will start, running the main method until its completion.
367
368
369A Real Example
370--------------
371
372Let's have some fun with a real library. We'll be using [Telethon](https://github.com/LonamiWebs/Telethon) to broadcast a message to our three best friends, all at the same time, thanks to the magic of `asyncio`. We'll dive right into the code, and then I'll explain our new friend `asyncio.wait(...)`:
373
374```python
375# broadcast.py
376import asyncio
377import sys
378
379from telethon import TelegramClient
380
381# (you need your own values here, check Telethon's documentation)
382api_id = 123
383api_hash = '123abc'
384friends = [
385 '@friend1__username',
386 '@friend2__username',
387 '@bestie__username'
388]
389
390# we will have to await things, so we need an async def
391async def main(message):
392 # start is a coroutine, so we need to await it to run it
393 client = await TelegramClient('me', api_id, api_hash).start()
394
395 # wait for all three client.send_message to complete
396 await asyncio.wait([
397 client.send_message(friend, message)
398 for friend in friends
399 ])
400
401 # and close our client
402 await client.disconnect()
403
404
405if __name__ == '__main__':
406 if len(sys.argv) != 2:
407 print('You must pass the message to broadcast!')
408 quit()
409
410 message = sys.argv[1]
411 asyncio.get_event_loop().run_until_complete(main(message))
412```
413
414Wait… how did that send a message to all three of
415my friends? The magic is done here:
416
417```python
418[
419 client.send_message(friend, message)
420 for friend in friends
421]
422```
423
424This list comprehension creates another list with three
425coroutines, the three `client.send_message(...)`.
426Then we just pass that list to `asyncio.wait`:
427
428```python
429await asyncio.wait([...])
430```
431
432This method, by default, waits for the list of coroutines to run until they've all finished. You can read more on the Python [documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait). Truly a good function to know about!
433
434Now whenever you have some important news for your friends, you can simply `python3 broadcast.py 'I bought a car!'` to tell all your friends about your new car! All you need to remember is that you need to `await` on coroutines, and you will be good. `asyncio` will warn you when you forget to do so.
435
436
437Extra Material
438--------------
439
440If you want to understand how `asyncio` works under the hood, I recommend you to watch this hour-long talk [Get to grips with asyncio in Python 3](https://youtu.be/M-UcUs7IMIM) 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 `asyncio` "scheduler" from scratch.