Member-only story
Why choose asyncawait instead of thread?
A common saying is that threads can do everything async/await
can do and are simpler. So why do people choose async/await
?
Rust is a low-level language that does not hide the complexity of coroutines. This is in contrast to languages like Go, where asynchrony occurs by default and programmers do not even need to consider it.
Smart programmers try to avoid complexity. Therefore, they see the additional complexity in async/await
and question why it is needed. This issue is particularly relevant when considering the existence of a reasonable alternative - operating system threads.
Let’s take a mental journey through async
.
Background overview
Usually, code is linear; one thing runs after another. It looks like this:
fn main() {
foo();
bar();
baz();
}
It’s very simple, right? However, sometimes you want to run many things at the same time. A typical example of this is a web server. Consider the following written in linear code:
fn main() -> io::Result<()> {
let socket = TcpListener::bind("0.0.0.0:80")?;
loop {
let (client, _) = socket.accept()?;
handle_client(client)?;
}
}
Imagine if handle_client
takes a few milliseconds and two clients try to connect to your web server at the same time. You will encounter a serious problem!
- Client #1 connects to the web server and is…