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