0
0
Rustprogramming~5 mins

Threads overview in Rust

Choose your learning style9 modes available
Introduction

Threads let your program do many things at the same time. This helps your program run faster and handle multiple tasks smoothly.

When you want to download files while still letting the user click buttons.
When you want to do heavy calculations without freezing the screen.
When you want to listen for messages and respond quickly.
When you want to run multiple tasks in parallel to save time.
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 starts 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 example counts numbers in a new thread while the main thread waits.
Rust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..5 {
            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. They print numbers with different delays, showing how threads work together.

Rust
use std::thread;
use std::time::Duration;

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

    for i in 1..4 {
        println!("Main counting: {}", i);
        thread::sleep(Duration::from_millis(300));
    }

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

Threads run independently but can share data carefully using special tools.

Always join threads to make sure they finish before the program ends.

Using threads can make programs faster but also more complex.

Summary

Threads let your program do many things at once.

Use thread::spawn to start a new thread.

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