Prevent the application from closing before all threads are done
So this is what I have:
extern crate time;
use std::thread;
fn main() {
let start = time::get_time();
println!("Starting application");
do_stuff();
println!("Total {:?}", time::get_time() - start);
}
fn do_stuff() {
for i in 0..4i32 {
thread::spawn(move || {
thread::sleep_ms(1);
println!("doing stuff {:?}", i);
});
}
}
For some reason I am not familiar with the application, I am not waiting for the threads in the function to complete and close do_stuff()
. So this is the result I get:
Starting application
Total Duration { secs: 0, nanos: 808482 }
Instead of something like
Starting application
doing stuff 1
doing stuff 2
doing stuff 3
doing stuff 4
Total Duration { secs: 0, nanos: 808482 }
How do I make the application wait for the threads to finish, even if the threads don't return anything?
+3
source to share
1 answer
The function spawn
returns a JoinHandle
. You can collect all the handles in a vector and call join
on them:
extern crate time;
use std::thread;
fn main() {
let start = time::get_time();
println!("Starting application");
do_stuff();
println!("Total {:?}", time::get_time() - start);
}
fn do_stuff() {
let handles: Vec<_> = (0..4).map(|i| {
thread::spawn(move || {
thread::sleep_ms(1);
println!("doing stuff {:?}", i);
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
+3
source to share