Chapter 2. Basic Async Rust
This chapter introduces the important components of using async in Rust and gives an overview of tasks, futures, async, and await. We cover context, pins, polling, and closures—important concepts for fully taking advantage of async programming in Rust. We have chosen the examples in this chapter to demonstrate the learning points; they may not necessarily be optimal for efficiency. The chapter concludes with an example of building an async audit logger for a sensitive program, pulling all the concepts together.
By the end of this chapter, you will be able to define a task and a future. You’ll also understand the more technical components of a future, including context and pins.
Understanding Tasks
In asynchronous programming, a task represents an asynchronous operation. The task-based asynchronous pattern (TAP) provides an abstraction over asynchronous code. You write code as a sequence of statements. You can read that code as though each statement completes before the next begins. For instance, let’s think about making a cup of coffee and toast, which requires the following steps:
-
Put bread in toaster
-
Butter toasted bread
-
Boil water in kettle
-
Pour milk
-
Put in instant coffee granules (not the best, but simplifies the example)
-
Pour boiled water
We can definitely apply async programming to speed this up, but first we need to break down all the steps into two big steps, make coffee and make toast, as follows:
-
Make coffee
-
Boil water in ...
-
Get Async Rust now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.