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 "Loop in main thread ended" is already printed before the "Spawned thread ended", but then the main thread waits.
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!("Spawned thread ended");
});
//thread::sleep(Duration::from_millis(1));
//thread::sleep(Duration::from_micros(1));
for i in 1..=5 {
println!(
"Hi number {} from the main thread! {:?}",
i,
thread::current().id()
);
thread::sleep(Duration::from_millis(1));
}
println!("Loop in 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)
Loop in 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)
Spawned thread ended
After ending: ThreadId(1)
Exiting