0PricingLogin
Learn Rust Coding · Lesson

Spawning Threads

Run code concurrently.

What Is a Thread?

A thread lets your program run code concurrently. The operating system can schedule multiple threads, so work can overlap.

Rust's standard library exposes threads through the std::thread module. These are native OS threads, sometimes called 1:1 threads.

In this lesson you will learn to start new threads and control how they run.

Spawning with thread::spawn

You create a new thread by calling thread::spawn and passing it a closure. The closure holds the code the new thread will run.

The call returns immediately with a JoinHandle, while the spawned thread runs in the background.

use std::thread;

fn main() {
    thread::spawn(|| {
        println!("hello from a thread");
    });
    println!("hello from main");
}

All lessons in this course

  1. Spawning Threads
  2. Moving Data into Threads
  3. Sharing with Arc and Mutex
  4. Joining and Collecting Results
← Back to Learn Rust Coding