First example with threads



examples/threads/try-threads/src/main.rs
use std::thread;
use std::time::Duration;

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

    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread! {:?}", i, thread::current().id());
            thread::sleep(Duration::from_millis(1));
        }
        println!("spwaned thread ended");
    });

    for i in 1..5 {
        println!("hi number {} from the main thread! {:?}", i, thread::current().id());
        thread::sleep(Duration::from_millis(1));
    }

    println!("main thread ended");
    handle.join().unwrap(); // waiting for the other thread to end.
    println!("After ending: {:?}", thread::current().id());

    println!("exiting");
}

Before starting: ThreadId(1)
hi number 1 from the main thread! ThreadId(1)
hi number 1 from the spawned thread! ThreadId(2)
hi number 2 from the main thread! ThreadId(1)
hi number 2 from the spawned thread! ThreadId(2)
hi number 3 from the main thread! ThreadId(1)
hi number 3 from the spawned thread! ThreadId(2)
hi number 4 from the main thread! ThreadId(1)
hi number 4 from the spawned thread! ThreadId(2)
main thread ended
hi number 5 from the spawned thread! ThreadId(2)
hi number 6 from the spawned thread! ThreadId(2)
hi number 7 from the spawned thread! ThreadId(2)
hi number 8 from the spawned thread! ThreadId(2)
hi number 9 from the spawned thread! ThreadId(2)
spwaned thread ended
After ending: ThreadId(1)
exiting