Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Simple thread with join

  • The solution is to save the handle of the thread and the use join to wait for its termination.
use std::thread;

fn main() {
    println!("Before starting: {:?}", thread::current().id());

    let handle = thread::spawn(|| {
        println!("In thread {:?}", thread::current().id());
    });

    println!("Before join: {:?}", thread::current().id());

    handle.join().unwrap();

    println!("After ending: {:?}", thread::current().id());
}
Before starting: ThreadId(1)
Before join: ThreadId(1)
In thread ThreadId(2)
After ending: ThreadId(1)

  • thread
  • spawn
  • join