all repos — gemini-redirect @ 772f5df37f7bd727dd575ea042b6d87b9b2e2529

blog/asyncio/index.html (view raw)

  1<!DOCTYPE html>
  2<html>
  3<head>
  4<meta charset="utf-8" />
  5<meta name="viewport" content="width=device-width, initial-scale=1" />
  6<title>An Introduction to Asyncio</title>
  7<link rel="stylesheet" href="../css/style.css">
  8</head>
  9<body>
 10<main>
 11<h1 class="title" id="an_introduction_to_asyncio"><a class="anchor" href="#an_introduction_to_asyncio">¶</a>An Introduction to Asyncio</h1>
 12<div class="date-created-modified">Created 2018-06-13<br>
 13Modified 2020-10-03</div>
 14<h2 id="index"><a class="anchor" href="#index">¶</a>Index</h2>
 15<ul>
 16<li><a href="#background">Background</a></li>
 17<li><a href="#input_output">Input / Output</a></li>
 18<li><a href="#diving_in">Diving In</a></li>
 19<li><a href="#a_toy_example">A Toy Example</a></li>
 20<li><a href="#a_real_example">A Real Example</a></li>
 21<li><a href="#extra_material">Extra Material</a></li>
 22</ul>
 23<h2 id="background"><a class="anchor" href="#background">¶</a>Background</h2>
 24<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>
 25<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>
 26<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:</p>
 27<pre><code class="language-python">def method():
 28	line 1
 29	line 2
 30	line 3
 31	line 4
 32	line 5
 33</code></pre>
 34<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 &quot;line 1&quot;, 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>
 35<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>
 36<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>
 37<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!</p>
 38<h2 id="input_output"><a class="anchor" href="#input_output">¶</a>Input / Output</h2>
 39<p>Before we go any further, let's first stop to talk about input and output, commonly known as &quot;IO&quot;. There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.</p>
 40<p>The first one is known as &quot;blocking IO&quot;. 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!</p>
 41<pre><code class="language-python">import socket
 42
 43# Setup a network socket and a very simple HTTP request.
 44# By default, sockets are open in blocking mode.
 45sock = socket.socket()
 46request = b'''HEAD / HTTP/1.0\r
 47Host: example.com\r
 48\r
 49'''
 50
 51# &quot;connect&quot; will block until a successful TCP connection
 52# is made to the host &quot;example.com&quot; on port 80.
 53sock.connect(('example.com', 80))
 54
 55# &quot;sendall&quot; will repeatedly call &quot;send&quot; until all the data in &quot;request&quot; is
 56# sent to the host we just connected, which blocks until the data is sent.
 57sock.sendall(request)
 58
 59# &quot;recv&quot; will try to receive up to 1024 bytes from the host, and block until
 60# there is any data to receive (or empty if the host closes the connection).
 61response = sock.recv(1024)
 62
 63# After all those blocking calls, we got out data! These are the headers from
 64# making a HTTP request to example.com.
 65print(response.decode())
 66</code></pre>
 67<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>
 68<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>
 69<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 &quot;not ready&quot;, 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:</p>
 70<pre><code>&lt;app&gt; Hey, I would like to read 16 bytes from this file
 71&lt;OS&gt; Okay, but the disk hasn't sent me the data yet
 72&lt;app&gt; Alright, I will do something else then
 73(a lot of computer time passes)
 74&lt;app&gt; Do you have my 16 bytes now?
 75&lt;OS&gt; Yes, here they are! &quot;Hello, world !!\n&quot;
 76</code></pre>
 77<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>
 78<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.</p>
 79<h2 id="diving_in"><a class="anchor" href="#diving_in">¶</a>Diving In</h2>
 80<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>
 81<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>
 82<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>
 83<div class="image-container">
 84<img src="eventloop.svg" alt="The Event Loop" />
 85<div class="image-caption"></div>
 86</div>
 87<p>
 88<p>That's silly you may think. Now not only we run our code but we also have to run some &quot;event loop&quot;. It doesn't sound beneficial at all. What are these events? Well, they are the IO events we talked about before!</p>
 89<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>
 90<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>
 91<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>
 92<div class="image-container">
 93<img src="awaitkwd1.svg" alt="Step 1, await keyword" />
 94<div class="image-caption"></div>
 95</div>
 96<p>
 97<div class="image-container">
 98<img src="awaitkwd2.svg" alt="Step 2, await keyword" />
 99<div class="image-caption"></div>
100</div>
101<p>
102<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 &quot;paused&quot; until an event occurs (for example, an &quot;event&quot; occurs when the request has been sent completely).</p>
103<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>
104<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:</p>
105<pre><code class="language-python">async def method(request):
106    prepare request
107    await send request
108
109    await receive request
110
111    process request
112    return result
113
114run in parallel (
115	method with request 1,
116	method with request 2,
117)
118</code></pre>
119<p>This is what the event loop will do on the above pseudo-code:</p>
120<pre><code>no events pending, can advance
121
122enter method with request 1
123	prepare request
124	await sending request
125pause method with request 1
126
127no events ready, can advance
128
129enter method with request 2
130	prepare request
131	await sending request
132pause method with request 2
133
134both requests are paused, cannot advance
135wait for events
136event for request 2 arrives (sending request completed)
137
138enter method with request 2
139	await receiving response
140pause method with request 2
141
142event for request 1 arrives (sending request completed)
143
144enter method with request 1
145	await receiving response
146pause method with request 1
147
148...and so on
149</code></pre>
150<p>You may be wondering &quot;okay, but threads work for me, so why should I change?&quot;. 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>
151<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>
152<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>
153<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 &quot;I want the future of my method to be ensured&quot;. 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>
154<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>
155<p>The <code>async def</code> functions are also called &quot;coroutines&quot;, 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.</p>
156<h2 id="a_toy_example"><a class="anchor" href="#a_toy_example">¶</a>A Toy Example</h2>
157<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>
158<p>Here is the <strong>synchronous version</strong>:</p>
159<pre><code class="language-python"># server.py
160import socket
161
162
163def server_method():
164	# create a new server socket to listen for connections
165	server = socket.socket()
166
167	# bind to localhost:6789 for new connections
168	server.bind(('localhost', 6789))
169
170	# we will listen for one client at most
171	server.listen(1)
172
173	# *block* waiting for a new client
174	client, _ = server.accept()
175
176	# *block* waiting for some data
177	data = client.recv(1024)
178
179	# reverse the data
180	data = data[::-1]
181
182	# *block* sending the data
183	client.sendall(data)
184
185	# close client and server
186	server.close()
187	client.close()
188
189
190if __name__ == '__main__':
191	# block running the server
192	server_method()
193</code></pre>
194<pre><code class="language-python"># client.py
195import socket
196
197
198def client_method():
199	message = b'Hello Server!\n'
200	client = socket.socket()
201
202	# *block* trying to stabilish a connection
203	client.connect(('localhost', 6789))
204
205	# *block* trying to send the message
206	print('Sending', message)
207	client.sendall(message)
208
209	# *block* until we receive a response
210	response = client.recv(1024)
211	print('Server replied', response)
212
213	client.close()
214
215
216if __name__ == '__main__':
217	client_method()
218</code></pre>
219<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>
220<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>
221<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>
222<p>Here is the <strong>asynchronous version</strong>:</p>
223<pre><code class="language-python"># server.py
224import asyncio
225import socket
226
227# get the default &quot;event loop&quot; that we will run
228loop = asyncio.get_event_loop()
229
230
231# notice our new &quot;async&quot; before the definition
232async def server_method():
233	server = socket.socket()
234	server.bind(('localhost', 6789))
235	server.listen(1)
236
237	# await for a new client
238	# the event loop can run other code while we wait here!
239	client, _ = await loop.sock_accept(server)
240
241	# await for some data
242	data = await loop.sock_recv(client, 1024)
243	data = data[::-1]
244
245	# await for sending the data
246	await loop.sock_sendall(client, data)
247
248	server.close()
249	client.close()
250
251
252if __name__ == '__main__':
253	# run the loop until &quot;server method&quot; is complete
254	loop.run_until_complete(server_method())
255</code></pre>
256<pre><code class="language-python"># client.py
257import asyncio
258import socket
259
260loop = asyncio.get_event_loop()
261
262
263async def client_method():
264	message = b'Hello Server!\n'
265	client = socket.socket()
266
267	# await to stabilish a connection
268	await loop.sock_connect(client, ('localhost', 6789))
269
270	# await to send the message
271	print('Sending', message)
272	await loop.sock_sendall(client, message)
273
274	# await to receive a response
275	response = await loop.sock_recv(client, 1024)
276	print('Server replied', response)
277
278	client.close()
279
280
281if __name__ == '__main__':
282	loop.run_until_complete(client_method())
283</code></pre>
284<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>
285<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 &quot;block&quot; 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>
286<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…</p>
287<pre><code class="language-python">def main():
288	...  # some code
289
290
291if __name__ == '__main__':
292	main()
293</code></pre>
294<p>…becomes this:</p>
295<pre><code class="language-python">import asyncio
296
297
298async def main():
299	...  # some code
300
301
302if __name__ == '__main__':
303	asyncio.get_event_loop().run_until_complete(main)
304</code></pre>
305<p>This is pretty much how most of your <code>async</code> scripts will start, running the main method until its completion.</p>
306<h2 id="a_real_example"><a class="anchor" href="#a_real_example">¶</a>A Real Example</h2>
307<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>:</p>
308<pre><code class="language-python"># broadcast.py
309import asyncio
310import sys
311
312from telethon import TelegramClient
313
314# (you need your own values here, check Telethon's documentation)
315api_id = 123
316api_hash = '123abc'
317friends = [
318	'@friend1__username',
319	'@friend2__username',
320	'@bestie__username'
321]
322
323# we will have to await things, so we need an async def
324async def main(message):
325	# start is a coroutine, so we need to await it to run it
326	client = await TelegramClient('me', api_id, api_hash).start()
327
328	# wait for all three client.send_message to complete
329	await asyncio.wait([
330		client.send_message(friend, message)
331		for friend in friends
332	])
333
334	# and close our client
335	await client.disconnect()
336
337
338if __name__ == '__main__':
339	if len(sys.argv) != 2:
340		print('You must pass the message to broadcast!')
341		quit()
342
343	message = sys.argv[1]
344	asyncio.get_event_loop().run_until_complete(main(message))
345</code></pre>
346<p>Wait… how did that send a message to all three of
347my friends? The magic is done here:</p>
348<pre><code class="language-python">[
349	client.send_message(friend, message)
350	for friend in friends
351]
352</code></pre>
353<p>This list comprehension creates another list with three
354coroutines, the three <code>client.send_message(...)</code>.
355Then we just pass that list to <code>asyncio.wait</code>:</p>
356<pre><code class="language-python">await asyncio.wait([...])
357</code></pre>
358<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>
359<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.</p>
360<h2 id="extra_material"><a class="anchor" href="#extra_material">¶</a>Extra Material</h2>
361<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> &quot;scheduler&quot; from scratch.</p>
362</main>
363</body>
364</html>
365