0
0
Rustprogramming~5 mins

Creating threads in Rust

Choose your learning style9 modes available
Introduction

Threads let your program do many things at the same time. This helps make your program faster and more efficient.

When you want to download multiple files at once.
When you want to run a timer while doing other tasks.
When you want to handle many users in a chat app simultaneously.
When you want to perform background calculations without stopping the main program.
Syntax
Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        // code to run in new thread
    });

    handle.join().unwrap();
}

thread::spawn starts a new thread and runs the code inside the closure.

handle.join() waits for the thread to finish before continuing.

Examples
This example creates a thread that prints a message, then waits for it to finish.
Rust
use std::thread;

fn main() {
    thread::spawn(|| {
        println!("Hello from a thread!");
    }).join().unwrap();
}
This thread counts from 1 to 3 and prints each number.
Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..4 {
            println!("Counting: {}", i);
        }
    });

    handle.join().unwrap();
}
Sample Program

This program runs two loops at the same time: one in the main thread and one in a new thread. You will see their outputs mixed because they run together.

Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..=5 {
            println!("Thread counting: {}", i);
        }
    });

    for i in 1..=3 {
        println!("Main thread counting: {}", i);
    }

    handle.join().unwrap();
}
OutputSuccess
Important Notes

Threads run independently, so their output order can change each time you run the program.

Always use join() to wait for threads to finish, or your program might end early.

Summary

Threads let your program do many things at once.

Use thread::spawn to create a new thread.

Use join() to wait for a thread to finish.