Member-only story

Why choose asyncawait instead of thread?

Beck Moulton
9 min readJun 12, 2024

--

A common saying is that threads can do everything async/awaitcan 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/awaitand 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_clienttakes 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…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet