CourseLesson 15 · Async and Unsafe RustSolve

Lesson 15

Async and Unsafe Rust

This lesson covers two features that sit apart from everything else you have written so far. Async lets a program wait on many slow operations, such as a network reply or a timer, using only one thread instead of one thread per wait. Unsafe lets you write a small number of operations the compiler cannot check for you, when you have a reason no safe code can give you.

Why Async

A network request, a file read, or a timer all involve waiting: the CPU has nothing to do until the answer arrives. A thread that is waiting like this is still a whole thread, with its own stack, doing no useful work. A program that needs to wait on thousands of network connections at once cannot afford a thread for each one.

Async code waits differently. An async function, once it reaches a point where it has to wait, hands control back instead of blocking the thread. A single thread can then hold many waiting async functions at once, switching between whichever one is ready to make progress. Nothing about async makes one calculation faster. It only lets a program wait on many things without paying for a thread each.

Running Async Code with tokio

The standard library defines async, await, and the Future trait, but it ships no way to actually run one. A separate crate, called a runtime, is needed to do that. tokio is the runtime almost every async Rust program uses.

[dependencies]
tokio = { version = "1", features = ["full"] }

Adding this to Cargo.toml downloads tokio from crates.io, the site that hosts published Rust packages, the next time the project is built.

async fn add_one(n: i32) -> i32 {
    n + 1
}

#[tokio::main]
async fn main() {
    let result = add_one(5).await;
    println!("{result}");
}
6
  • async fn add_one(...) declares a function that returns a Future instead of running immediately. Its body only runs once that Future is awaited.

  • #[tokio::main] rewrites async fn main into a plain fn main that starts a tokio runtime and runs the async body on it. Every async program needs something like this at the top: main itself cannot be async on its own.

  • add_one(5).await runs the function and waits for its result, the same way a normal function call waits, except the thread is free to do other work while an async function is waiting on something slower than plain arithmetic.

Futures Are Lazy

Calling an async function does not run it. It builds a value, a Future, describing the work to do. Nothing happens until that value is awaited.

async fn greet() {
    println!("inside greet");
}

#[tokio::main]
async fn main() {
    let future = greet();
    println!("created the future");
    future.await;
    println!("after awaiting");
}
created the future
inside greet
after awaiting

created the future prints before inside greet, even though greet() is called first. The call only builds the Future. println!("inside greet") only runs once future.await runs it.

Key idea

A Future that is never awaited never runs at all, not even partway. The compiler warns about this: futures do nothing unless you .await or poll them. Treat that warning the same way as an unused Result, as a sign that something the program meant to do was left out.

Running Futures at the Same Time

Awaiting one future after another still waits for each one in turn.

use std::time::Duration;

async fn task(name: &str, ms: u64) {
    println!("{name} starting");
    tokio::time::sleep(Duration::from_millis(ms)).await;
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    task("one", 100).await;
    task("two", 50).await;
}
one starting
one done
two starting
two done

tokio::time::sleep waits without blocking the thread, the async version of the thread::sleep you might reach for in ordinary code. Even so, awaiting task("one", ...) before starting task("two", ...) means two cannot start until one has completely finished. tokio::join! starts every future it is given right away, and waits for all of them together.

use std::time::Duration;

async fn task(name: &str, ms: u64) {
    println!("{name} starting");
    tokio::time::sleep(Duration::from_millis(ms)).await;
    println!("{name} done");
}

#[tokio::main]
async fn main() {
    tokio::join!(task("one", 100), task("two", 50));
}
one starting
two starting
two done
one done

Both tasks start before either one waits. two finishes first because its wait is shorter, even though it started second. join! does not return until every future passed to it has finished.

tokio::spawn runs a future in the background immediately, the async equivalent of thread::spawn, returning a handle you can await later for its result.

async fn compute() -> i32 {
    let mut total = 0;
    for n in 1..=5 {
        total += n;
    }
    total
}

#[tokio::main]
async fn main() {
    let handle = tokio::spawn(compute());
    let result = handle.await.unwrap();
    println!("{result}");
}
15

handle.await waits for the spawned future to finish and returns its result, wrapped in a Result the same way thread::spawn’s join is: .unwrap() is needed because the spawned future could have panicked.

Raw Pointers

Every pointer you have used so far, &T and &mut T, is checked by the compiler: it always points at a live value, and the borrowing rules are enforced. A raw pointer, written *const T or *mut T, carries none of those guarantees. Creating one is safe. Reading through one is not.

fn main() {
    let n = 5;
    let pointer: *const i32 = &n;

    unsafe {
        println!("{}", *pointer);
    }
}
5
  • let pointer: *const i32 = &n; builds a raw pointer from an ordinary reference. This line needs no unsafe, because forming a raw pointer cannot go wrong by itself.

  • *pointer dereferences it, reading the value it points at. This is the part that needs unsafe: nothing checks that pointer still points at a live i32.

Leave the unsafe block out, and the compiler refuses to build the program.

error[E0133]: dereference of raw pointer is unsafe and
              requires unsafe block
 --> src/main.rs:5:20
  |
5 |     println!("{}", *pointer);
  |                    ^^^^^^^^ dereference of raw pointer
  |
  = note: raw pointers may be null, dangling or unaligned;
    they can violate aliasing rules and cause data races:
    all of these are undefined behavior

*mut T works the same way, and also allows writing through the pointer.

fn main() {
    let mut n = 5;
    let pointer: *mut i32 = &mut n;

    unsafe {
        *pointer += 10;
    }

    println!("{n}");
}
15

The unsafe Block

An unsafe block does not turn off the borrow checker or any of the other rules you have relied on so far. It only allows a handful of extra operations inside it, such as dereferencing a raw pointer, that the compiler cannot verify are safe. Writing unsafe is a promise to the compiler, made by you, that the operation is actually fine here.

A function can be marked unsafe too, when calling it correctly depends on something the compiler cannot check, such as which values are valid to pass in. Calling one still needs an unsafe block, the same as dereferencing a raw pointer does.

unsafe fn double(n: *mut i32) {
    unsafe {
        *n *= 2;
    }
}

fn main() {
    let mut value = 21;
    let pointer: *mut i32 = &mut value;

    unsafe {
        double(pointer);
    }

    println!("{value}");
}
42

The body of double wraps *n *= 2 in its own unsafe block, even though double is already an unsafe fn. Being an unsafe fn only changes what its callers must do, wrapping the call in unsafe to acknowledge they have checked whatever the function needs to be safe. It does not make the operations inside the function’s own body automatically allowed: leaving out the inner unsafe block still compiles, but the compiler warns, because the block is what marks, at the exact line doing something risky, that it was allowed on purpose.

Nothing about a raw pointer stops it from outliving the value it points at, the way a reference is stopped by the borrow checker.

fn dangling() -> *const i32 {
    let n = 5;
    &n as *const i32
}

fn main() {
    let pointer = dangling();
    unsafe {
        println!("{}", *pointer);
    }
}

This compiles, with a warning: a dangling pointer is safe, but dereferencing one is undefined behavior. n is dropped the moment dangling returns, so pointer points at memory that no longer holds an i32. Dereferencing it does not reliably crash or print a clear error. It reads whatever happens to be at that address now, which can look fine for a while and then fail somewhere far away, which is exactly why unsafe code deserves extra care.

When unsafe Is Worth Reaching For

Almost all of the Rust you write should stay safe. Reach for unsafe only for a specific, narrow reason:

  • Calling a function written in another language, such as C, which Rust cannot check at all.

  • Building a safe type for others to use, such as a data structure that needs one raw-pointer trick inside it, while everything it exposes stays checked as normal.

  • A performance-critical section where a safe version has been measured to be too slow, and the unsafe version has been checked by hand against every rule it must not break.

Key idea

“I could not get the borrow checker to accept this” is not a reason to reach for unsafe. The borrow checker rejecting a design is almost always a sign to change the design, not to step around it.

Common Mistakes

Forgetting .await

Calling an async function without awaiting it builds a Future and throws it away. Nothing inside that function ever runs, not even the first line. The compiler’s warning, futures do nothing unless you .await or poll them, is not optional reading. Treat it as a bug report.

Blocking Inside Async Code

std::thread::sleep and other ordinary blocking calls stop the whole thread, including every other future that thread was juggling, not just the one that called it. Inside an async fn, use the async version of whatever operation is waiting, such as tokio::time::sleep instead of std::thread::sleep, so only that one future waits.

Reaching for unsafe to Silence an Error

The borrow checker rejects a design for a reason. Wrapping code in unsafe to make an error go away removes the check without removing the underlying problem. The mistake the compiler was pointing at is still there. It has only stopped being reported.

Dereferencing a Pointer Past Its Value’s Lifetime

A raw pointer keeps working, syntactically, long after the value it pointed at is gone. Nothing about the type itself records whether that value is still alive. Treat every raw pointer as suspect until you can say, in one sentence, why the memory it points at is still valid at the moment you dereference it.

Reference

Written asWhat it does
async fn f()A function that returns a Future instead of running at once.
f().awaitRuns the future and waits for its result.
#[tokio::main]Turns async fn main into a runnable program with a runtime.
tokio::join!(…)Runs several futures together, waits for all of them.
tokio::spawn(f)Runs a future in the background, returns a handle to it.
tokio::time::sleepWaits without blocking the thread.
*const TA raw pointer for reading, with no compiler-checked guarantees.
*mut TA raw pointer for reading and writing.
unsafe { … }A block allowing operations the compiler cannot verify are safe.
unsafe fnA function whose caller must check its own safety rules.

Check what stuck

The practice sheet for this lesson has 40 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.

Start practice →