A Rust Async Primer-Pt. 1
These days, if you’re writing code in a reasonably modern language, it’s difficult to escape the idea of asynchronous programming. If you search for the most popular programming languages of 2022, every single entry in the list supports asynchronous programming. Most of them even use the same keywords in their syntax, async, and await. This article will be the first in a series of articles that will present the general concepts, followed by a brief discussion of how async is implemented in Rust, and finally some sample code to demonstrate the concepts.
Intro to Asynchronicity
Let’s start by clearing up some common misunderstandings. First Concurrency is the act of performing multiple tasks simultaneously. For example, I can both walk and chew bubble gum at the same time (most days). A different example would be making a pot of coffee while I read the morning paper. Both of these are examples of concurrency but the means by which they are achieved differ. Walking and chewing gum at the same time is an example of parallelism since I can do both things simultaneously. Making a pot of coffee while reading the paper is an example of synchronicity since I can’t physically do both tasks simultaneously. Instead, I prep the coffee maker and start it, then begin reading my paper. When the pot is done, I then stop reading, pour a cup, and go back to reading. I can work on both tasks at once, just not at the same time. In other words, I move on to another task, while waiting for the previous one to complete.
In languages that support async programming, in very simplified terms, async code is implemented using a compiler-generated state machine. This state machine uses the
await keyword to break up the execution units into smaller chunks, creating a code block from the beginning of the method to the first
await boundary as one task. The next execution chunk would be all the code between the first
await, and the second
await, if there is one. I mention this detail to point out that threads do not enter into the picture. They can, and certainly do, but the point is that asynchronous code has nothing to do with threads.