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 fake work)

  • We can easily start a new thread using the spawn function of the thread crate.
  • We even have two loops one in the main thread and one in the created thread to "do some work". It seems to work.
  • There is a slight problem though. Our main program might end before the thread can do the actual work and this example we don't even see that.
use std::thread;

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

    thread::spawn(|| {
        println!("In thread {:?}", thread::current().id());
        for i in 1..10000000 {
            let _n = i + i;
        }
    });

    for i in 1..10000000 {
        let _n = i + i;
    }

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