RRust By Example
intermediateConcurrency

Thread Basic

Spawn threads and join them.

Thread Basic

Spawn threads and join them.

Difficulty

Intermediate

Code

rust
use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..=5 {
            println!("spawned thread: {}", i);
            thread::sleep(Duration::from_millis(10));
        }
    });

    for i in 1..=3 {
        println!("main thread: {}", i);
        thread::sleep(Duration::from_millis(10));
    }

    handle.join().unwrap();
}

Explanation

This example demonstrates how to use thread basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples