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

thread::spawn creates OS threads. join() waits for completion.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

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

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Concurrency Examples