Skip to content

Commit 7903cc4

Browse files
authored
Merge pull request #236 from nrc/adv-aa-1
Write the first half of the advanced async/await chapter
2 parents 6444462 + 3997c79 commit 7903cc4

File tree

5 files changed

+149
-79
lines changed

5 files changed

+149
-79
lines changed

src/07_workarounds/02_err_in_async_blocks.md

-48
This file was deleted.

src/SUMMARY.md

-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,6 @@
6262
- [TODO: Cancellation and Timeouts]()
6363
- [TODO: `FuturesUnordered`]()
6464
- [Workarounds to Know and Love](07_workarounds/01_chapter.md)
65-
- [`?` in `async` Blocks](07_workarounds/02_err_in_async_blocks.md)
6665
- [`Send` Approximation](07_workarounds/03_send_approximation.md)
6766
- [Recursion](07_workarounds/04_recursion.md)
6867
- [`async` in Traits](07_workarounds/05_async_in_traits.md)

src/part-guide/adv-async-await.md

+145-30
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,160 @@
22

33
## Unit tests
44

5+
How to unit test async code? The issue is that you can only await from inside an async context, and unit tests in Rust are not async. Luckily, most runtimes provide a convenience attribute for tests similar to the one for `async main`. Using Tokio, it looks like this:
6+
7+
```rust,norun
8+
#[tokio::test]
9+
async fn test_something() {
10+
// Write a test here, including all the `await`s you like.
11+
}
12+
```
13+
14+
There are many ways to configure the test, see the [docs](https://docs.rs/tokio/latest/tokio/attr.test.html) for details.
15+
16+
There are some more advanced topics in testing async code (e.g., testing for race conditions, deadlock, etc.), and we'll cover some of those [later]() in this guide.
17+
18+
519
## Blocking and cancellation
620

7-
- Two important concepts to be aware of early, we'll revisit in more detail as we go along
8-
- Cancellation
9-
- How to do it
10-
- drop a future
11-
- cancellation token
12-
- abort functions
13-
- Why it matters, cancellation safety (forward ref)
14-
- Blocking
15-
- IO and computation can block
16-
- why it's bad
17-
- how to deal is a forward ref to io chapter
21+
Blocking and cancellation are important to keep in mind when programming with async Rust. These concepts are not localised to any particular feature or function, but are ubiquitous properties of the system which you must understand to write correct code.
22+
23+
### Blocking IO
24+
25+
We say a thread (note we're talking about OS threads here, not async tasks) is blocked when it can't make any progress. That's usually because it is waiting for the OS to complete a task on its behalf (usually I/O). Importantly, while a thread is blocked, the OS knows not to schedule it so that other threads can make progress. This is fine in a multithreaded program because it lets other threads make progress while the blocked thread is waiting. However, in an async program, there are other tasks which should be scheduled on the same OS thread, but the OS doesn't know about those and keeps the whole thread waiting. This means that rather than the single task waiting for its I/O to complete (which is fine), many tasks have to wait (which is not fine).
26+
27+
We'll talk soon about non-blocking/async I/O. For now, just know that non-blocking I/O is I/O which the async runtime knows about and so will only the current task will wait, the thread will not be blocked. It is very important to only use non-blocking I/O from an async task, never blocking I/O (which is the only kind provided in Rust's standard library).
28+
29+
### Blocking computation
30+
31+
You can also block the thread by doing computation (this is not quite the same as blocking I/O, since the OS is not involved, but the effect is similar). If you have a long-running computation (with or without blocking I/O) without yielding control to the runtime, then that task will never give the runtime's scheduler a chance to schedule other tasks. Remember that async programming uses cooperative multitasking. Here a task is not cooperating, so other tasks won't get a chance to get work done. We'll discuss ways to mitigate this later.
32+
33+
There are many other ways to block a whole thread, and we'll come back to blocking several times in this guide.
34+
35+
### Cancellation
36+
37+
Cancellation means stopping a future (or task) from executing. Since in Rust (and in contrast to many other async/await systems), futures must be driven forward by an external force (like the async runtime), if a future is no longer driven forward then it will not execute any more. If a future is dropped (remember, a future is just a plain old Rust object), then it can never make any more progress and is canceled.
38+
39+
Cancellation can be initiated in a few ways:
40+
41+
- By simply dropping a future (if you own it).
42+
- Calling [`abort`](https://docs.rs/tokio/latest/tokio/task/struct.JoinHandle.html#method.abort) on a task's 'JoinHandle' (or an `AbortHandle`).
43+
- Via a [`CancellationToken`](https://docs.rs/tokio-util/latest/tokio_util/sync/struct.CancellationToken.html) (which requires the future being canceled to notice the token and cooperatively cancel itself).
44+
- Implicitly, by a function or macro like [`select`](https://docs.rs/tokio/latest/tokio/macro.select.html).
45+
46+
The middle two are specific to Tokio, though most runtimes provide similar facilities. Using a `CancellationToken` requires cooperation of the future being canceled, but the others do not. In these other cases, the canceled future will get no notification of cancellation and no opportunity to clean up (besides its destructor). Note that even if a future has a cancellation token, it can still be canceled via the other methods which won't trigger the cancellation token.
47+
48+
From the perspective of writing async code (in async functions, blocks, futures, etc.), the code might stop executing at any `await` (including hidden ones in macros) and never start again. In order for your code to be correct (specifically to be *cancellation safe*), it must work correctly whether it completes normally or whether it terminates at any await point[^cfThreads].
49+
50+
```rust,norun
51+
async fn some_function(input: Option<Input>) {
52+
let Some(input) = input else {
53+
return; // Might terminate here (`return`).
54+
};
55+
56+
let x = foo(input)?; // Might terminate here (`?`).
57+
58+
let y = bar(x).await; // Might terminate here (`await`).
59+
60+
// ...
61+
62+
// Might terminate here (implicit return).
63+
}
64+
```
65+
66+
An example of how this can go wrong is if an async function reads data into an internal buffer, then awaits the next datum. If reading the data is destructive (i.e., cannot be re-read from the original source) and the async function is canceled, then the internal buffer will be dropped, and the data in it will be lost. It is important to consider how a future and any data it touches will be impacted by canceling the future, restarting the future, or starting a new future which touches the same data.
67+
68+
We'll be coming back to cancellation and cancellation safety a few times in this guide, and there is a whole [chapter]() on the topic in the reference section.
69+
70+
[^cfThreads]: It is interesting to compare cancellation in async programming with canceling threads. Canceling a thread is possible (e.g., using `pthread_cancel` in C, there is no direct way to do this in Rust), but it is almost always a very, very bad idea since the thread being canceled can terminate anywhere. in contrast, canceling an async task can only happen at an await point. As a consequence, it is very rare to cancel an OS thread without terminating the whole porcess and so as a programmer, you generally don't worry about this happening. In async Rust however, cancellation is definitely something which *can* happen. We'll be discussing how to deal with that as we go along.
71+
72+
## Async blocks
73+
74+
A regular block (`{ ... }`) groups code together in the source and creates a scope of encapsulation for names. At runtime, the block is executed in order and evaluates to the value of its last expression (or the unit type (`()`) if there is no trailing expression).
75+
76+
Similarly to async functions, an async block is a deferred version of a regular block. An async block scopes code and names together, but at runtime it is not immediately executed and evaluates to a future. To execute the block and obtain the result, it must be `await`ed. E.g.:
77+
78+
```rust,norun
79+
let s1 = {
80+
let a = 42;
81+
format!("The answer is {a}")
82+
};
83+
84+
let s2 = async {
85+
let q = question().await;
86+
format!("The question is {q}")
87+
};
88+
```
89+
90+
If we were to execute this snippet, `s1` would be a string which could be printed, but `s2` would be a future; `question()` would not have been called. To print `s2`, we first have to `s2.await`.
91+
92+
An async block is the simplest way to start an async context and create a future. It is commonly used to create small futures which are only used in one place.
93+
94+
Unfortunately, control flow with async blocks is a little quirky. Because an async block creates a future rather than straightforwardly executing, it behaves more like a function than a regular block with respect to control flow. `break` and `continue` cannot go 'through' an async block like they can with regular blocks; instead you have to use `return`:
95+
96+
```rust,norun
97+
loop {
98+
{
99+
if ... {
100+
// ok
101+
continue;
102+
}
103+
}
104+
105+
async {
106+
if ... {
107+
// not ok
108+
// continue;
109+
110+
// ok - continues with the next execution of the `loop`, though note that if there was
111+
// code in the loop after the async block that would be executed.
112+
return;
113+
}
114+
}.await
115+
}
116+
```
117+
118+
To implement `break` you would need to test the value of the block (a common idiom is to use [`ControlFlow`](https://doc.rust-lang.org/std/ops/enum.ControlFlow.html) for the value of the block, which also allows use of `?`).
119+
120+
Likewise, `?` inside an async block will terminate execution of the future in the presence of an error, causing the `await`ed block to take the value of the error, but won't exit the surrounding function (like `?` in a regular block would). You'll need another `?` after `await` for that:
121+
122+
```rust,norun
123+
async {
124+
let x = foo()?; // This `?` only exits the async block, not the surrounding function.
125+
consume(x);
126+
Ok(())
127+
}.await?
128+
```
129+
130+
Annoyingly, this often confuses the compiler since (unlike functions) the 'return' type of an async block is not explicitly stated. You'll probably need to add some type annotations on variables or use turbofished types to make this work, e.g., `Ok::<_, MyError>(())` instead of `Ok(())` in the above example.
131+
132+
A function which returns an async block is pretty similar to an async function. Writing `async fn foo() -> ... { ... }` is roughly equivalent to `fn foo() -> ... { async { ... } }`. In fact, from the caller's perspective they are equivalent, and changing from one form to the other is not a breaking change. Furthermore, you can override one with the other when implementing an async trait (see below). However, you do have to adjust the type, making the `Future` explicit in the async block version: `async fn foo() -> Foo` becomes `fn foo() -> impl Future<Output = Foo>` (you might also need to make other bounds explicit, e.g., `Send` and `'static`).
133+
134+
You would usually prefer the async function version since it is simpler and clearer. However, the async block version is more flexible since you can execute some code when the function is called (by writing it outside the async block) and some code when the result is awaited (the code inside the async block).
135+
136+
137+
## Async closures
138+
139+
- closures
140+
- coming soon (https://github.com/rust-lang/rust/pull/132706, https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html)
141+
- async blocks in closures vs async closures
142+
143+
144+
## Lifetimes and borrowing
145+
146+
- Mentioned the static lifetime above
147+
- Lifetime bounds on futures (`Future + '_`, etc.)
148+
- Borrowing across await points
149+
- I don't know, I'm sure there are more lifetime issues with async functions ...
150+
18151

19152
## `Send + 'static` bounds on futures
20153

21154
- Why they're there, multi-threaded runtimes
22155
- spawn local to avoid them
23156
- What makes an async fn `Send + 'static` and how to fix bugs with it
24157

158+
25159
## Async traits
26160

27161
- syntax
@@ -36,18 +170,6 @@
36170
- history and async-trait crate
37171

38172

39-
## Async blocks and closures
40-
41-
- async block syntax
42-
- what it means
43-
- using an async block in a function returning a future
44-
- subtype of async method
45-
- closures
46-
- coming soon (https://github.com/rust-lang/rust/pull/132706, https://blog.rust-lang.org/inside-rust/2024/08/09/async-closures-call-for-testing.html)
47-
- async blocks in closures vs async closures
48-
- errors in async blocks
49-
- https://rust-lang.github.io/async-book/07_workarounds/02_err_in_async_blocks.html
50-
51173
## Recursion
52174

53175
- Allowed (relatively new), but requires some explicit boxing
@@ -56,10 +178,3 @@
56178
- https://blog.rust-lang.org/2024/03/21/Rust-1.77.0.html#support-for-recursion-in-async-fn
57179
- async-recursion macro (https://docs.rs/async-recursion/latest/async_recursion/)
58180

59-
60-
## Lifetimes and borrowing
61-
62-
- Mentioned the static lifetime above
63-
- Lifetime bounds on futures (`Future + '_`, etc.)
64-
- Borrowing across await points
65-
- I don't know, I'm sure there are more lifetime issues with async functions ...

src/part-guide/concurrency-primitives.md

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
- different versions in different runtimes/other crates
99
- focus on the Tokio versions
1010

11+
From [comment](https://github.com/rust-lang/async-book/pull/230#discussion_r1829351497): A framing I've started using is that tasks are not the async/await form of threads; it's more accurate to think of them as parallelizable futures. This framing does not match Tokio and async-std's current task design; but both also have trouble propagating cancellation. See parallel_future and tasks are the wrong abstraction for more.
12+
13+
1114
## Join
1215

1316
- Tokio/futures-rs join macro

src/part-guide/streams.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
- Taking a future instead of a closure
2222
- Some example combinators
2323
- unordered variations
24+
- StreamGroup
2425

2526
## Implementing an async iterator
2627

0 commit comments

Comments
 (0)