csperkins.org

Advanced Systems Programming H (2020-2021)

Lecture 8: Coroutines and Asynchronous Programming

Lecture 8 discusses coroutines and asynchronous programming. The limitations of multithreaded applications with blocking I/O are reviewed, and the use of asynchronous functions, coroutines, to multiplex several concurrent non-block I/O operations onto a single thread is discussed. The resulting asynchronous programming model is discussed, along with its benefits and limitations.

Part 1: Coroutines and Asynchronous Programming

The first part of the lecture discusses the motivation of using coroutines and asynchronous programming. It reviews the problems caused by blocking I/O operations, how these lead to the use of multi-threaded code, and how the affect the structure of programs.

00:00:00.000 In this lecture, I’ll move on from

00:00:02.307 talking about concurrency, and talk about something

00:00:04.614 closely related, which is coroutines and asynchronous

00:00:06.920 programming.

 

00:00:09.300 In this part, I’ll start by talking

00:00:11.460 about why we might want asynchronous programming,

00:00:13.619 talk about some of the motivation.

 

00:00:15.570 In the second part, I’ll talk about

00:00:17.633 the idea of coroutines, and how they're

00:00:19.697 implemented in terms of the async and

00:00:21.760 await primitives, and finally, in the last

00:00:23.823 part of the lecture, I’ll talk about

00:00:25.886 some design patterns asynchronous code.

 

00:00:29.670 So what's the motivation? Why do we

00:00:32.661 want coroutines? Why do we want asynchronous

00:00:35.653 code?

 

00:00:36.180 It’s all to do with overlapping I/O

00:00:38.832 and computation, it’s all to do with

00:00:41.484 avoiding multi-threading, and

 

00:00:42.720 building non-blocking alternatives to the I/O primitives.

 

00:00:49.170 If we look at regular I/O code,

00:00:52.310 you tend to have functions which look

00:00:55.450 like the example we have on the

00:00:58.590 top of the slide; the read_exact() function.

 

00:01:01.830 What this function is doing, is reading

00:01:04.156 an exact amount of data from some

00:01:06.482 input stream, and storing it in a

00:01:08.808 buffer.

 

00:01:09.240 For example, it might be reading from

00:01:11.126 a file, or it might be reading

00:01:13.012 from a socket.

 

00:01:13.920 If it's reading from a TCP socket,

00:01:17.179 for example,

 

00:01:18.210 then it it's possible, depending on the

00:01:21.046 congestion control, depending on what the sender

00:01:23.882 is doing, it’s possible that the socket

00:01:26.718 doesn't have the requested amount of data

00:01:29.555 available to read.

 

00:01:30.870 And so this function has to work

00:01:33.888 in a loop, repeatedly reading from the

00:01:36.906 socket until it's received the amount of

00:01:39.924 data that that's been requested.

 

00:01:42.180 And this works, and it's simple and

00:01:45.532 it's straightforward.

 

00:01:46.590 The problem with this type of code,

00:01:50.342 though, is twofold.

 

00:01:52.050 Firstly, the I/O operations can be very

00:01:55.493 slow. The function can block for a

00:01:58.935 long time, while reading from the file

00:02:02.378 descriptor.

 

00:02:02.970 And that could just be because the

00:02:04.775 disk is slow, or it could be

00:02:06.579 because the network is slow, or it

00:02:08.384 could be because it's blocked because it's

00:02:10.188 reading from the network and there's nothing

00:02:11.993 available to read and it has to

00:02:13.798 wait for the sender to send more

00:02:15.602 data.

 

00:02:15.960 So calls to the read() function() can

00:02:19.279 take many millions of cycles. They can

00:02:22.598 be incredibly slow.

 

00:02:24.120 The other issue here is that when

00:02:27.633 the read() function is called, it blocks

00:02:31.146 the thread.

 

00:02:32.250 The thread of execution stops while waiting

00:02:35.069 for that period of time, while the

00:02:37.889 read() call is completing.

 

00:02:39.600 And this prevents other computations from running,

00:02:42.345 and if the thread is also part

00:02:45.090 of your user interface, it disrupts the

00:02:47.836 user experience.

 

00:02:48.720 So, ideally, we want to be able

00:02:50.972 to overlap the I/O and the computation.

00:02:53.224 We want to be able to run

00:02:55.477 them concurrently.

 

00:02:56.220 Ideally, want to be able to allow

00:02:58.377 multiple concurrent I/O operations.

 

00:03:02.970 The way this has traditionally been solved,

00:03:05.579 of course, is by using multiple threads.

00:03:08.188 The usual solution to this, is to

00:03:10.798 move the blocking I/O operations out of

00:03:13.407 the main thread, and put them into

00:03:16.016 a separate thread which does the I/O,

00:03:18.625 and then reports back once the data

00:03:21.235 is available.

 

00:03:22.080 And, in Rust, the way you might

00:03:24.172 do this

 

00:03:24.870 is outlined in the code on the

00:03:27.840 slide. You create a channel, and you

00:03:30.810 spawn a thread to perform I/O.

00:03:33.355 And that thread then sends the results

00:03:36.325 back down the channel, and the rest

00:03:39.295 of the program continues, and overlaps with

00:03:42.264 the execution of the I/O operation.

 

00:03:44.910 And this is relatively simple, in that

00:03:47.911 it doesn't really require any new language

00:03:50.911 or runtime features. It’s the same blocking

00:03:53.912 calls. it's the same multithreading functions,

00:03:56.484 we have anyway.

 

00:03:57.870 And it doesn’t really change the way

00:04:00.656 we do I/O.

 

00:04:01.950 It's not changing the fundamental model of

00:04:06.086 either I/O or threading.

 

00:04:08.550 But it does mean we have to

00:04:10.743 move the I/O code to a separate

00:04:12.937 thread,

 

00:04:13.350 which is some programming overhead.

 

00:04:17.790 It also has the advantage, though,

00:04:19.624 that it can run in parallel if

00:04:21.765 the system really does have multiple cores.

00:04:23.905 And it's safe, especially in Rust,

00:04:25.739 because the ownership rules prevent data races

00:04:27.880 so it's easy, and relatively straightforward,

00:04:29.714 to push the code into a separate

00:04:31.854 thread.

 

00:04:36.420 The disadvantages

 

00:04:39.120 are that it adds complexity.

 

00:04:43.230 Creating a thread and Rust isn't difficult.

00:04:46.753 But it's harder than not creating a

00:04:50.277 thread.

 

00:04:50.880 Spawning a thread, partitioning the I/O operations

00:04:54.597 into a separate thread, isn't conceptually difficult

00:04:58.313 in Rust, but it complicates the code.

 

00:05:02.130 It's a more complex programming model.

00:05:05.559 It obfuscates the structure of the code.

 

00:05:09.660 It's relatively resource heavy.

 

00:05:14.700 You have the overheads of context switching

00:05:17.608 to the separate threads, and each thread

00:05:20.516 has its own stack, its own memory

00:05:23.425 overhead.

 

00:05:23.940 And that's not an enormous overhead,

00:05:26.124 but it is an overhead. And it's

00:05:28.673 a much heavier overhead than just running

00:05:31.221 the read() call within the main thread.

 

00:05:33.870 And the fact that the threads can

00:05:36.522 run concurrently,

 

00:05:37.380 the fact that the threads can run

00:05:39.517 in parallel if you have multicore hardware,

00:05:41.654 is actually a relatively limited benefit,

00:05:43.485 because the thread spends most of its

00:05:45.622 time blocked waiting for I/O anyway.

00:05:47.454 So it's a bit of a waste

00:05:49.591 starting a new thread, just to call

00:05:51.727 a read() function which then blocks 90%

00:05:53.864 of its lifetime.

 

00:06:00.450 So we can certainly perform blocking I/O

00:06:05.693 using multiple threads.

 

00:06:08.040 But it's problematic.

 

00:06:10.380 It’s high overhead in a lot of

00:06:13.116 cases. You've got context switch overheads,

00:06:15.461 you've got the memory overheads due to

00:06:18.197 the separate stack,

 

00:06:19.470 you've got the scheduler overheads, and there’s

00:06:23.018 not that much benefit of parallelism anyway,

00:06:26.565 because it blocks for most of the

00:06:30.113 time.

 

00:06:30.720 And some systems allow you to avoid

00:06:33.035 this. In Erlang, for example, the threading

00:06:35.351 is pretty lightweight, but in most systems

00:06:37.666 this is not the case, and it's

00:06:39.982 a relatively high overhead to start multiple

00:06:42.297 threads to perform I/O.

 

00:06:48.030 We'd like we'd like something more lightweight

00:06:50.775 as an alternative. We'd like to somehow

00:06:53.519 be able to multiplex I/O operations in

00:06:56.264 a single thread,

 

00:06:57.540 we'd like to somehow

 

00:07:00.000 allow I/O operations to complete asynchronously,

00:07:02.837 without having to have separate threads of

00:07:06.147 control.

 

00:07:06.720 So, it would be desirable to provide

00:07:09.223 a mechanism which allows us to start

00:07:11.725 asynchronous I/O,

 

00:07:12.540 start an I/O operation, and let it

00:07:14.791 run in the background, and somehow allow

00:07:17.042 us to poll the kernel to see

00:07:19.292 if it has finished yet,

 

00:07:21.000 all running within a single application thread.

 

00:07:24.900 The idea would be that you start

00:07:27.416 the I/O, and then it continues in

00:07:29.932 the background while the

 

00:07:31.470 program continues performing other computations. And then,

00:07:35.357 at some point, once the data is

00:07:39.245 available,

 

00:07:39.900 either there's a callback which gets executed

00:07:42.142 to provide the data, or the main

00:07:44.384 thread can just poll it and say

00:07:46.626 “has it finished?”, and if it has,

00:07:48.868 it can pull the data in.

 

00:07:55.170 And this is also a reasonably common

00:07:58.796 abstraction. If you’re a C programmer,

00:08:01.904 this is the select() function in the

00:08:05.530 Berkeley sockets API, for example.

 

00:08:08.220 And there's a bunch of new,

00:08:10.818 higher performance, versions of this, such as

00:08:13.848 epoll(), if you're a Linux or an

00:08:16.879 Android programmer, or the kqueue abstraction in

00:08:19.909 FreeBSD, or macOS, or on the iPhone.

 

00:08:23.040 Or, if you're a Windows programmer,

00:08:25.445 I/O completion ports do something very similar.

00:08:28.250 And this tends to get wrapped in

00:08:31.056 libraries, such as libevent, or libev,

00:08:33.461 or libuv, which was trying to provide

00:08:36.266 common portable APIs for them.

 

00:08:38.370 And, in Rust, the mio library also

00:08:43.178 provides a portable abstraction for this.

 

00:08:47.400 The functionality that these things provide,

00:08:49.616 is the ability to trigger non-blocking operations.

00:08:52.202 They provide you a way of saying

00:08:54.787 “read asynchronously” or “write asynchronously’ from a

00:08:57.373 file or a socket,

 

00:08:58.950 and they provide a poll() abstraction,

00:09:01.494 so you can periodically check to see

00:09:04.462 if it completed and retrieve the data.

 

00:09:07.530 And they're actually pretty efficient.

 

00:09:10.380 They meet the goals of efficiency,

00:09:12.697 they meet the goals of only running

00:09:15.399 in a single thread, and

 

00:09:17.430 they build on features of the operating

00:09:20.607 system kernels that provide asynchronous I/O.

 

00:09:23.430 The problem with them, is that they

00:09:25.586 require, again, restructuring the code to avoid

00:09:27.742 blocking.

 

00:09:31.980 And this is an example. This is

00:09:35.533 network code using sockets and select() function

00:09:39.086 in C. And what we see here

00:09:42.639 is the select() call, where you pass

00:09:46.192 it

 

00:09:46.800 the three parameters, the set of readable

00:09:49.648 file descriptors, the set of writeable file

00:09:52.497 descriptors, the set of file descriptors might

00:09:55.345 deliver errors, and a timeout.

 

00:09:57.480 You have to bundle up all the

00:10:00.081 file descriptors that may have outstanding asynchronous

00:10:02.682 I/O, fill them into these parameters,

00:10:04.911 call it, and then poll each of

00:10:07.512 these in turn to see if the

00:10:10.113 FD_ISSET calls, to see which of those

00:10:12.714 different file descriptors, have data available to

00:10:15.315 read or write.

 

00:10:16.530 And it's a relatively low-level API,

00:10:18.891 which is reasonably well suited to C

00:10:21.646 programming,

 

00:10:22.140 but it does require quite a restructure

00:10:24.619 of the code. This is no longer

00:10:27.099 as simple as just calling read() as

00:10:29.578 part of a loop. It’s restructuring the

00:10:32.057 whole program as an event loop,

00:10:34.182 where you poll on different file descriptors,

00:10:36.662 different sockets.

 

00:10:37.470 And the alternative libraries I mentioned,

00:10:40.427 such as libuv for C programming,

00:10:43.383 such as mio for Rust programming,

 

00:10:46.440 make this more portable, and they a

00:10:48.789 little bit higher level, and they remove

00:10:51.138 some of the boilerplate, but conceptually you're

00:10:53.488 doing the same thing.

 

00:10:54.930 Conceptually you have to restructure the program

00:10:57.138 as an event loop, where you trigger

00:10:59.346 the asynchronous I/O, and every so often

00:11:01.554 you poll it to see if it's

00:11:03.762 completed. And it involves restructuring the code.

 

00:11:12.180 Now, these approaches have the advantage that

00:11:15.638 they're very efficient.

 

00:11:17.220 Because the asynchrony is handled by the

00:11:22.064 operating system kernel,

 

00:11:24.240 a single thread can very efficiently handle

00:11:27.547 multiple sockets. All it does is trigger

00:11:30.853 the asynchronous operation, and a kernel thread

 

00:11:34.260 handles all the rest.

 

00:11:36.540 The mechanisms to run these operations concurrently

00:11:40.736 are built into the kernel, and they're

00:11:44.931 pretty efficient.

 

00:11:46.230 But it requires us to rewrite the

00:11:49.279 application code.

 

00:11:50.250 It requires us to restructure the application

00:11:53.300 as something which looks different. As something

00:11:56.350 which has an event loop, which polls

00:11:59.400 the data sources and reassembles the data.

 

00:12:02.550 So, fundamentally, we have two choices.

 

00:12:05.880 We can structure the code as a

00:12:08.534 set of multiple threads, which involves spawning

00:12:11.189 a thread and restructuring the code as

00:12:13.843 a set of multiple threads which pass

00:12:16.497 the data back once we've successfully read

00:12:19.152 the data.

 

00:12:20.010 Or we can restructure the code using

00:12:24.673 the asynchronous I/O primitives, which involves

 

00:12:28.770 turning it into an event loop with

00:12:32.480 polling and so on. Again, both ways

00:12:36.190 involve a fairly fundamental rewrite of the

00:12:39.900 code to get the these efficiency gains.

 

00:12:43.710 What we would like is to be

00:12:46.113 able to get this efficiency, get the

00:12:48.517 efficiency of non-blocking I/O, in a much

00:12:50.920 more usable manner.

 

00:12:52.050 And the idea is that coroutines and

00:12:54.032 asynchronous code are one way of doing

00:12:56.015 that, so that's what I'll talk about

00:12:57.997 in the next part.

 

00:13:01.860 So.

 

00:13:03.540 How do we overlap I/O and competition?

 

00:13:06.510 Well, if we want to do it

00:13:09.123 today, we have a spawn multiple threads,

00:13:11.737 or sue the non-blocking I/O primitives provided

00:13:14.350 by the kernel through functions such as

00:13:16.963 select(), or mio, or libuv.

 

00:13:18.930 And these all work, but they introduce

00:13:21.549 complexity into the programming model.

 

00:13:23.520 Is there a better way?

 

00:13:25.800 Maybe. This is what asynchronous I/O and

00:13:27.573 coroutines are about, which we'll talk about

00:13:29.347 in the next part.

Part 2: async and await

The second part of the lecture discusses how coroutines and asynchronous code can be used to support I/O multiplexing on a single thread. It reviews what is a coroutine, and the way coroutines can execute concurrently to their caller by repeatedly yielding results; and it reviews how this is implemented. The way this can be used to support asynchronous I/O operations is outlined, leading to a description of asynchronous functions in Python and Rust. The need for runtime support is outlined.

 

00:00:00.500 In this part, I want to talk

00:00:03.000 about coroutines and asynchronous code, and the

00:00:05.500 runtime support needed to execute asynchronous code.

 

00:00:10.000 As we discussed in the previous part,

00:00:13.118 blocking I/O is problematic.

 

00:00:15.000 Code, like we see in the example

00:00:17.450 at the top of the slide,

00:00:19.550 that calls blocking I/O functions, such as

00:00:22.000 read(), stalls the execution of the program

00:00:24.450 while waiting for those calls to complete.

 

00:00:27.000 And the work-arounds for this, using multiple

00:00:30.300 threads or asynchronous I/O functions, such as

00:00:33.600 select(), require extensive restructuring of the code.

 

00:00:37.000 The goal of using coroutines with asynchronous

00:00:39.914 code is to allow I/O and computation

00:00:42.828 to be performed concurrently on a single

00:00:45.742 thread, without restructuring the code. The hope

00:00:48.656 is that this will avoid the overheads

00:00:51.570 of multithreading, while retaining the original code

00:00:54.484 structure.

 

00:00:55.000 Essentially we hope to transform the blocking

00:00:57.815 code shown at the top of the

00:01:00.630 slide, into the asynchronous, non-blocking, code such

00:01:03.446 at that shown at the bottom.

00:01:05.859 And provide the language runtime with the

00:01:08.674 ability to execute those asynchronous functions concurrently

00:01:11.489 with low-overhead asynchronous I/O operations.

 

00:01:16.000 The programming model we’re considering structures the

00:01:18.962 code as a set of concurrent coroutines

00:01:21.923 that accept data from I/O sources and

00:01:24.885 yield in place of blocking.

00:01:27.000 The coroutines execute concurrently, overlapping I/O and

00:01:30.468 computation, all within a single thread of

00:01:33.936 execution, and so avoid the overhead of

00:01:37.405 multithreading.

 

00:01:38.000 To understand this programming model, though,

00:01:40.957 we must first ask what is a

00:01:44.407 coroutine?

 

00:01:45.000 Well, if we consider a normal function,

00:01:47.765 we see that it’s called, executes for

00:01:50.530 a while, and returns a result.

 

00:01:53.000 A coroutine, in contrast, has the ability

00:01:56.010 to pause its execution. Rather than return

00:01:59.020 a single value, or even a list

00:02:02.030 of values, it lazily generates a sequence

00:02:05.040 of values.

 

00:02:06.000 The slide shows an example, written in

00:02:08.698 Python. In this case, the countdown() function

00:02:11.397 is a coroutine that yields a sequence

00:02:14.095 of integers, counting down to zero from

00:02:16.794 the value given as its argument.

00:02:19.106 We see that calling countdown() with the

00:02:21.805 parameter 5, yields the values 5,

00:02:24.118 4, 3, 2, and 1, and that

00:02:26.816 these can be processed by a for

00:02:29.515 loop.

 

00:02:30.000 Importantly, the countdown() function is not returning

00:02:33.471 a single value, comprising a list of

00:02:36.942 numbers counting down. Rather, calling countdown() returns

00:02:40.412 a generator object.

 

00:02:42.000 By itself, a generator object does nothing.

 

00:02:46.000 But the generator object implements a next()

00:02:49.052 method. And the for loop protocol in

00:02:52.104 Python takes a generator object and repeatedly

00:02:55.156 calls that next() method.

 

00:02:57.000 And each time next() is called,

00:02:59.511 the function executes until it reaches the

00:03:02.439 yield statement, then returns the next value.

00:03:05.368 Or it executes until the function ends,

00:03:08.297 when it returns None to indicate that

00:03:11.226 the generator has completed.

 

00:03:13.000 Essentially, the function is turned into a

00:03:16.000 heap allocated generator object that maintains state,

00:03:19.000 executes lazily in response to calls to

00:03:22.000 next(), and repeatedly yields the different values.

 

00:03:27.000 Coroutines in Python do nothing until the

00:03:29.650 next() function is called on the generator

00:03:32.300 object representing the coroutine. Normally this happens

00:03:34.950 automatically, as part of the operation of

00:03:37.600 a for loop, but we can also

00:03:40.250 call it manually, as we see here.

 

00:03:43.000 In this example, the grep() function is

00:03:46.465 a coroutine, and the call to g

00:03:49.930 = grep(“python”) instantiates the generator object.

 

00:03:53.000 But instantiating the generator doesn’t cause it

00:03:55.819 to run. The print() call at the

00:03:58.638 start of the grep() function doesn’t execute

00:04:01.457 until we call the next() method,

00:04:03.873 for example, forcing the coroutine to run

00:04:06.692 until it yields.

 

00:04:08.000 In this case, the function yields to

00:04:10.380 consume a value, so we call send()

00:04:12.760 rather than next(), and pass in a

00:04:15.140 value. And we do this repeatedly,

00:04:17.180 passing in different values each time,

00:04:19.220 and each time causing a single iteration

00:04:21.600 of the while loop in the grep()

00:04:23.980 function to execute.

 

00:04:27.000 We see that the coroutine is a

00:04:29.429 function that executes concurrently to the rest

00:04:31.859 of the code.

 

00:04:33.000 It’s event driven. It only executes when

00:04:35.862 the runtime calls its next() or send()

00:04:38.724 method, which causes its execution to resume

00:04:41.585 until it next yields, at which point

00:04:44.447 control passes back to the runtime.

 

00:04:47.000 In the examples, we’ve only had a

00:04:49.594 single coroutine executing at once, but it’s

00:04:52.188 entirely possible to start several different coroutines,

00:04:54.782 and have the runtime loop, calling their

00:04:57.376 next() methods. This will cause the different

00:04:59.971 coroutines to execute concurrently, each one executing

00:05:02.565 for a while until it yields to

00:05:05.159 the next.

 

00:05:06.000 It’s an approach that’s sometime known as

00:05:09.811 cooperative multitasking.

 

00:05:11.000 The system context switches each time a

00:05:13.726 coroutine yields the processor, and if it

00:05:16.453 doesn’t yield, it keeps running.

 

00:05:18.500 This is how Microsoft Windows 3.1,

00:05:21.269 and the Macintosh System 7, handled multitasking.

 

00:05:27.000 But it gives us a basis for

00:05:29.450 efficient I/O handling within a single thread.

 

00:05:32.000 We structure the code to execute within

00:05:35.085 a thread as a set of coroutines

00:05:38.170 that trigger an asynchronous I/O operation,

00:05:40.815 and yield rather than blocking on I/O.

 

00:05:44.000 And we label the functions as being

00:05:47.085 async. This is a label that tells

00:05:50.170 the language runtime that those functions are

00:05:53.256 coroutines that call asynchronous I/O operations.

 

00:05:56.000 And I/O operations that would normally block

00:05:59.056 are labelled in the code with an

00:06:02.112 await tag. This causes the coroutine to

00:06:05.168 trigger the asynchronous version of that I/O

00:06:08.224 operation, then yield, passing control to another

00:06:11.280 coroutine while the I/O is performed.

 

00:06:14.000 This provides concurrent I/O, without parallelism.

00:06:17.560 The coroutines operate concurrently, but within a

00:06:21.713 single thread.

 

00:06:23.000 The calls to await tell the kernel

00:06:25.887 to start an asynchronous I/O operation,

00:06:28.363 and yield the file descriptor representing that

00:06:31.250 operation to the runtime.

 

00:06:33.000 The runtime operates in a loop.

00:06:35.437 It repeatedly calls select(), and adds the

00:06:38.280 coroutines that yielded any readable or writable

00:06:41.122 file descriptors to the end of a

00:06:43.965 run queue. Then, it resumes the coroutine

00:06:46.808 at the head of the run queue,

00:06:49.651 calling its next() or send() method as

00:06:52.494 appropriate.

 

00:06:53.000 And when that coroutine yields, and returns

00:06:55.406 a file descriptor, it’s moved to the

00:06:57.812 list of blocked tasks, and its file

00:07:00.219 descriptor is added to the set to

00:07:02.625 be polled in future.

00:07:04.000 And the loop continues, calling select() again.

 

00:07:10.000 An async function is therefore a function

00:07:13.069 that performs asynchronous I/O operations and that

00:07:16.138 can operate as a coroutine. The slide

00:07:19.208 shows an example in Python.

 

00:07:21.500 The async functions are executed asynchronously by

00:07:24.412 the runtime, in response to I/O events,

00:07:27.324 and the program is written as a

00:07:30.236 set of async functions.

 

00:07:32.000 The main() function calls into the runtime

00:07:35.041 giving it the top-level async function to

00:07:38.081 run. This starts the asynchronous runtime,

00:07:40.687 starts it polling for I/O, and runs

00:07:43.728 until that async function completes.

 

00:07:46.000 It’s a widely supported model. Coroutines,

00:07:48.727 in the form of async functions,

00:07:51.455 exist in Python, JavaScript, C#, Rust,

00:07:54.182 and in other languages.

 

00:07:59.000 Within an async function, await statements cause

00:08:02.150 the function to yield control to the

00:08:05.300 runtime while an asynchronous I/O operation is

00:08:08.450 performed.

 

00:08:09.000 Executing an await statement yields control to

00:08:11.631 the runtime. It puts the coroutine into

00:08:14.262 a queue to be woken at some

00:08:16.893 later time, when the I/O operation has

00:08:19.524 completed.

 

00:08:20.000 If another coroutine is ready to execute,

00:08:23.085 then the runtime schedules the yielding function

00:08:26.170 to wake-up once the I/O completes,

00:08:28.815 and control passes to that other coroutine.

 

00:08:32.000 Otherwise, runtime blocks until either this,

00:08:34.455 or some other, I/O operation becomes ready,

00:08:37.318 then passes control back to the corresponding

00:08:40.182 async function.

 

00:08:44.000 The resulting asynchronous code follows structure of

00:08:48.130 the blocking code.

 

00:08:50.000 If we look at the async version

00:08:52.420 of the read_exact() function in Rust,

00:08:54.493 for example, we see that the only

00:08:56.913 differences are the async and await annotations,

00:08:59.333 and that the input is declared to

00:09:01.752 be something that implements the AsyncRead trait,

00:09:04.172 rather than the Read trait.

 

00:09:06.000 The code structure remains unchanged, aside from

00:09:08.625 the call to main that wraps the

00:09:11.250 async functions into a call to start

00:09:13.875 the runtime. And the compiler and runtime

00:09:16.500 work together to generate code that efficiently

00:09:19.125 executes the asynchronous I/O operations.

 

00:09:24.000 How is this implemented in Rust?

 

00:09:27.000 Well, in the Python code we saw

00:09:29.543 earlier, the coroutine was instantiated as a

00:09:32.087 generator object with a next() method that

00:09:34.630 allowed it to run and yield the

00:09:37.173 next value.

 

00:09:38.000 Rust does something similar. The async functions

00:09:40.884 are compiled into instances of structs that

00:09:43.768 maintain the function state, and that implement

00:09:46.652 a trait known as Future. The Future

00:09:49.536 trait has a member type that describes

00:09:52.420 the return value, and defines a poll()

00:09:55.304 function that runs the function until it

00:09:58.188 yields an instance of an enum.

00:10:00.660 And that’s either Ready, with the yielded

00:10:03.544 value, or Pending to indicate that the

00:10:06.428 async function is waiting for I/O.

 

00:10:09.000 The details differ between Rust and Python,

00:10:11.882 as you might expect, but the concepts

00:10:14.765 are the same.

 

00:10:19.000 And that concludes this discussion of coroutines

00:10:21.730 and asynchronous code.

 

00:10:23.000 In the next part, I’ll talk briefly

00:10:25.520 about how to use async functions,

00:10:27.680 and about the advantages and disadvantages of

00:10:30.200 this approach to structuring code.

Part 3: Design Patterns for Asynchronous Code

The final part of the lecture discusses how to structure and compose asynchronous functions, and reviews the need to avoid blocking operations and long-running calculations in asynchronous functions. The benefits and problems of the asynchronous programming model are discussed.

00:00:00.000 In this final part, I want to

00:00:02.800 talk about some design patterns asynchronous code,

00:00:05.600 and about the advantages and disadvantages of

00:00:08.400 asynchronous programming.

 

00:00:09.300 I’ll start by talking about some of

00:00:11.410 the design patterns. I’ll talk about how

00:00:13.520 you compose future values, about the need

00:00:15.631 to avoid blocking I/O, and the need

00:00:17.741 to avoid long-running computations in asynchronous code.

 

00:00:23.011 So in writing async functions, I think

00:00:25.318 the goal should be to make these

00:00:27.625 functions as small, and as limited scope,

00:00:29.932 as possible.

 

00:00:30.691 An async function should perform a single,

00:00:33.538 well-defined task. It should read and parse

00:00:36.384 a file, or it should read,

00:00:38.824 parse, process, and respond to a network

00:00:41.671 request, for example.

 

00:00:42.991 And it functions are structured in this

00:00:45.989 way, they tend to be fairly straightforward

00:00:48.988 and written a fairly natural style,

00:00:51.558 and compose pretty straightforwardly.

 

00:00:53.371 The Rust async libraries provide some combinator

00:00:56.938 functions that can help compose futures.

00:00:59.996 That can help come combine future values

00:01:03.563 and produce a new value.

 

00:01:06.211 And there are functions, such as read_exact(),

00:01:09.387 which allow it to read a an

00:01:12.562 exact number of bytes, such as select()

00:01:15.738 to allow it to respond to different

00:01:18.914 Futures which

 

00:01:19.921 are operating concurrently, and functions such as

00:01:23.288 for_each() and and_then(), which can ease the

00:01:26.656 composition of the asynchronous functions.

 

00:01:29.161 And sometimes these are helpful, sometimes they

00:01:31.597 just obfuscate the code. But there are

00:01:34.034 a number of functions that can work

00:01:36.470 with, and combine, Futures in the cases

00:01:38.907 that they’re useful.

 

00:01:42.451 When writing asynchronous code, there’s two fundamental

 

00:01:47.041 constraints that you need to be aware

00:01:50.471 of.

 

00:01:51.061 The first, due to the nature of

00:01:54.879 asynchronous code, is that it multiplexes multiple

00:01:58.698 I/O operations onto a single thread.

 

00:02:02.071 And the runtime has to provide asynchronous-aware

00:02:05.286 versions of all of these different I/O

00:02:08.502 operations.

 

00:02:09.061 It has to provide asynchronous reads and

00:02:11.933 writes to files, asynchronous reads and writes

00:02:14.806 to the network, TCP, UDP, and Unix

00:02:17.678 sockets, and to other types of network

00:02:20.551 protocols.

 

00:02:21.061 And in all of these cases,

00:02:22.892 it has to provide a non-blocking version

00:02:25.028 of the I/O operation, that returns a

00:02:27.165 Future that can interact with the runtime.

 

00:02:29.401 Rather than natively calling the blocking function

00:02:33.536 provided by the operating system, it has

00:02:37.670 to wrap the underlying the operating system

00:02:41.805 provided async I/O operations, and wrap them

00:02:45.940 into Futures.

 

00:02:47.221 And, importantly, it doesn't interact well with

00:02:51.040 blocking I/O.

 

00:02:52.231 If you call the synchronous version of

00:02:54.988 read(), for example, to read from a

00:02:57.745 file, and that blocks, it will block

00:03:00.503 the entire runtime, because the runtime is

00:03:03.260 operating within the context of a single

00:03:06.017 thread,

 

00:03:06.511 and the underlying system doesn't know about

00:03:10.466 Futures.

 

00:03:11.131 The programmer has to have the discipline

00:03:15.154 to avoid calling the blocking functions of

00:03:19.176 the code, otherwise the entire asynchronous runtime

00:03:23.199 grinds to a halt while that blocking

00:03:27.222 operation completes.

 

00:03:28.471 And this, to some extent, runs the

00:03:30.772 risk of fragmenting the ecosystem. It means

00:03:33.073 that libraries which are supposed to be

00:03:35.374 used in an asynchronous context have to

00:03:37.675 be written to use asynchronous functions,

00:03:39.647 have to be written to call await(),

00:03:41.948 have to be written to use the

00:03:44.249 asynchronous versions of the I/O libraries.

 

00:03:46.321 And if anyone, any of the library

00:03:49.039 authors, implementing any of those libraries forgets,

00:03:51.758 then you run the risk of that

00:03:54.476 blocking the runtime,

 

00:03:55.741 losing concurrency, losing the performance.

 

00:03:59.671 And this is a potential source of

00:04:02.407 bugs, because the Rust compiler, the Rust

00:04:05.143 language, can't catch this sort of behaviour.

00:04:07.879 The programmer is required to have the

00:04:10.615 discipline to avoid the blocking I/O operations.

 

00:04:16.591 Similarly, the programmer has to avoid long

00:04:21.600 running computations.

 

00:04:23.131 Control passing between different Futures, between different

00:04:26.690 async functions, is explicit. Control passing happens

00:04:30.249 when you call it await, to wait

00:04:33.807 for an I/O operation.

 

00:04:35.941 At that point, the next runnable Future,

00:04:39.971 the next runnable async function, is scheduled.

 

00:04:44.101 But in the same way that calling

00:04:46.949 blocking functions is problematic, because it causes

00:04:49.797 the runtime to stop while that function

00:04:52.645 blocks, if instead you don't call await,

00:04:55.493 and you perform some long running computation,

 

00:04:58.441 the runtime won't know, won’t be able

00:05:01.254 to switch away from that computation,

00:05:03.665 and it will starve the other tasks

00:05:06.477 from running.

 

00:05:07.381 If you have a long running computation,

00:05:10.511 you need to spawn a separate thread,

 

00:05:13.741 and explicitly pass messages to and from

00:05:17.076 that thread, to avoid

 

00:05:19.081 starving the other asynchronous computations.

 

00:05:22.951 And again, the language, the runtime,

00:05:25.186 doesn't help with this. The programmer needs

00:05:27.794 to be aware that you must avoid

00:05:30.402 long running computations, as well as blocking

00:05:33.010 I/O, in the context of an asynchronous

00:05:35.618 runtime.

 

00:05:36.091 So we're getting good performance, but we're

00:05:38.526 getting good performance by limiting what the

00:05:40.961 programmer can do in the async runtime,

00:05:43.396 and by requiring them to have the

00:05:45.830 discipline to make sure that they follow

00:05:48.265 those limitations.

 

00:05:54.391 So, is the asynchronous approach to programming

00:05:57.765 a good approach?

 

00:05:59.311 Should we all be switching to asynchronous

00:06:00.991 code in the future?

 

00:06:06.091 Well…

 

00:06:09.691 The use of async and await lets

00:06:13.425 us structure the code in a way

00:06:17.159 that allows us to efficiently multiplex large

00:06:20.893 numbers of I/O operations on a single

00:06:24.628 thread.

 

00:06:25.261 And this can give a very natural

00:06:28.087 programming model when you're performing operations which

00:06:30.913 are very heavily I/O bound.

 

00:06:33.031 It lets us structure code, which performs

00:06:35.740 asynchronous non-blocking I/O, in a way that

00:06:38.448 looks very similar to code that uses

00:06:41.157 blocking I/O.

 

00:06:42.031 That can efficiently multiplex multiple I/O operations

00:06:46.225 onto a single thread,

 

00:06:48.721 efficiently allow them to run concurrently,

00:06:52.192 without the overheads of starting-up multiple threads.

 

00:06:56.341 So for I/O bound tasks, this can

00:06:59.146 be very, very efficient, and very natural.

 

00:07:04.951 But.

 

00:07:07.531 It's problematic, if there are blocking operations,

00:07:10.466 as we saw a minute ago,

 

00:07:13.081 because the blocking operations lock-up the entire

00:07:15.986 runtime, and not just that one task.

 

00:07:18.991 And it means all the libraries,

00:07:21.589 that use blocking calls need to be

00:07:24.620 updated to use these asynchronous I/O operations.

 

00:07:27.751 And this either means everything has to

00:07:30.362 use asynchronous I/O, or people need to

00:07:32.972 build two versions all the libraries.

00:07:35.210 Some that are synchronous, and use the

00:07:37.820 blocking operations, and some which are asynchronous.

 

00:07:40.531 It’s also problematic when it comes to

00:07:43.506 long running computations. Again, as we saw,

00:07:46.481 they starve the other tasks, because the

00:07:49.456 runtime only switches away when you call

00:07:52.431 asynchronous operations, when you call await.

 

00:07:55.081 And so, if you're trying to mix

00:07:58.337 long-running, compute-heavy, functions with asynchronous I/O functions

00:08:01.593 and I/O-bound tasks, it gets to be

00:08:04.850 problematic, and tends to starve to I/O

00:08:08.106 tasks.

 

00:08:08.671 And this is a problem which is

00:08:11.426 familiar to anyone who wrote code on

00:08:14.182 Windows 3.1 or on the MacIntosh System

00:08:16.937 7

 

00:08:17.431 And it led to real interactivity problems

00:08:20.608 with those applications, where applications would just

00:08:23.784 not yield the CPU, and it would

00:08:26.961 prevent the multitasking from working for a

00:08:30.137 while.

 

00:08:30.691 I worry that by promoting asynchronous code,

00:08:34.578 we're just introducing the same hard to

00:08:38.466 debug

 

00:08:39.121 problems with task starvation, into the next

00:08:44.280 generation of applications.

 

00:08:46.591 The asynchronous I/O works really well when

00:08:49.560 you have a lot of

 

00:08:51.781 I/O-bound tasks. It doesn't mix well with

00:08:55.802 compute-bound tasks.

 

00:09:01.741 And, to some extent, I wonder whether

00:09:04.593 we really need the asynchronous I/O? Whether

00:09:07.446 we really need this for performance?

 

00:09:09.991 It's certainly true that threads are more

00:09:14.323 expensive than async functions, and async tasks,

00:09:18.655 in the runtime.

 

00:09:20.611 But threads are not that expensive.

 

00:09:24.931 A properly configured modern machine can run

00:09:28.274 many, many thousands of threads, without any

00:09:31.616 great difficulty.

 

00:09:32.671 The laptop I’m recording this lecture on,

00:09:36.231 for example, which is a low-end MacBook

00:09:39.792 Air with a Core i5 processor,

00:09:42.843 is running about 2200 threads in normal

00:09:46.404 everyday use.

 

00:09:47.521 And If you look up the documentation

00:09:50.563 for, for example, the Varnish web cache,

00:09:53.606 which is a caching web proxy that’s

00:09:56.648 quite popular in data centres,

 

00:09:58.921 the documentation says it's common to configure

00:10:02.926 this with 500 or 1000 threads,

00:10:06.358 at minimum, but they rarely recommend running

00:10:10.363 more than 5000 threads.

 

00:10:12.751 And, I think, unless you're doing something

00:10:15.831 very, very unusual, it's likely you can

00:10:18.911 just spawn a thread, or use a

00:10:21.991 pre-configured thread pool, and perform blocking I/O,

00:10:25.071 and just communicate using channels, and the

00:10:28.151 performance will be just fine.

 

00:10:30.451 Even if this means spawning up thousands

00:10:34.597 of threads.

 

00:10:35.881 Modern servers can run thousands, or tens

00:10:39.617 of thousands, of simultaneous threads without any

00:10:43.354 great difficulty.

 

00:10:44.521 Threading is not that expensive these days.

 

00:10:49.111 And asynchronous I/O can give a performance

00:10:52.987 benefit.

 

00:10:53.641 But that performance benefit is usually not

00:10:57.787 that great.

 

00:10:59.071 So my recommendation is,

 

00:11:01.471 choose asynchronous programming because you prefer the

00:11:04.353 programming style, if you like.

 

00:11:06.511 But don't choose it for performance reasons,

00:11:09.848 unless you really sure that it will

00:11:13.184 improve performance. Threading is not as expensive

00:11:16.521 as you think.

 

00:11:21.451 And that concludes our discussion of coroutines

00:11:24.762 and asynchronous I/O.

 

00:11:26.281 As we've seen, blocking I/O can be

00:11:29.491 problematic. It's problematic because it forces you

00:11:32.700 to write multi-threaded code, which has

 

00:11:35.551 a reputation as being high overhead.

00:11:37.927 Or it's problematic because you have to

00:11:40.700 structure your code as a select loop.

00:11:43.472 And in both of these cases there's

00:11:46.245 a restructuring of the code needed.

 

00:11:48.721 The use of coroutines and asynchronous code,

00:11:52.085 in the best cases, can give you

00:11:55.448 a structure for I/O-heavy code, which allows

00:11:58.812 you to perform asynchronous I/O operations without

00:12:02.175 greatly restructuring the code, and just involves

00:12:05.539 some small number of annotations,

 

00:12:08.041 and switching to use the async version

00:12:11.247 of the runtime.

 

00:12:12.721 And, in those cases it's quite a

00:12:15.306 natural programming model, and it works very

00:12:17.892 well.

 

00:12:18.361 It does, though, run the risk of

00:12:21.029 fragmenting the ecosystem into async aware,

00:12:23.317 and non-async aware functions, and I think

00:12:25.985 it runs the risk of

 

00:12:27.991 introducing hard to find bugs with blocking

00:12:32.153 code, and with CPU hogging code.

 

00:12:35.821 Is it worth it?

 

00:12:38.611 I don't know, maybe.

 

00:12:40.951 It gives very natural code in some

00:12:43.363 cases, and very high performance code in

00:12:45.776 some cases, I think it can work

00:12:48.188 very well in those cases.

 

00:12:50.011 In other cases, in other applications,

 

00:12:53.491 the multi-threaded, blocking, version of the code

00:12:57.080 is just as natural to write,

00:13:00.157 and also scales very well.

 

00:13:02.821 Different applications have different requirements, and I

00:13:07.333 would encourage experimentation, rather than just diving

00:13:11.845 straight in to using asynchronous functions and

00:13:16.356 await.

 

00:13:17.101 In the next lecture, we’ll move on,

00:13:18.981 and instead of talking about concurrency,

00:13:20.591 we'll move on to talk about security.

Discussion

Lecture 8 discussed coroutines and asynchronous programming. It started by explaining why blocking I/O is problematic, because I/O operations are slow and block execution of the thread will they're performed. The lecture then outlined the two traditional approach to addressing these concerns: either spawning an additional thread to perform the I/O, or introducing asynchronous I/O primitives, backed by kernel threads, to perform I/O on behalf of the user program. It noted that both of these approaches work, but threads have relatively high overhead, and both approach require significant code restructuring.

The second part of the lecture then discussed the use of coroutines and asynchronous code, in the form of the async and await primitives. These allow asynchronous execution of I/O operations with low overhead and only limited restructuring of the code, to label functions as being able to execute as asynchronous coroutines and the label scheduling points where the system may block due to I/O. The result is widely used, efficient, and, in many cases, requires only limited code changes.

The lecture also discussed, briefly, the runtime support needed to support asynchronous code in the form of coroutines, and outlined how this is implemented in Rust using polling and a runtime such as Tokio. It noted the limitations around avoiding blocking operations and long-running computations, and noted the similarity of these to the cooperative multitasking used in Mac System 7 and Windows 3.1.

Finally, the lecture considered the overheads and costs of using asynchronous I/O versus multiple threads.

Discussion will focus on the need for asynchronous I/O operations using coroutines, and the claimed performance benefits versus the costs of restructuring the code.