all repos — gemini-redirect @ c67ef7846816c9b1416819617421a2389450ad33

content/blog/asyncio/index.md (view raw)

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