- thread
- spawn
- sleep
- join
- current
First example with threads
- spawn will create a new thread. We can use thread::current().id() to get the id of the current thread.
- join in the main thread will block till the other thread stops.
- We can see "main thread ended" is already printed before the "spwan thread ended", but then the main thread waits.
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