在所有线程完成之前阻止应用程序关闭

时间:2015-06-25 09:40:34

标签: multithreading rust

所以这就是我所拥有的:

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

}

由于某种原因,我不熟悉应用程序不会等待函数do_stuff()中的线程完成和关闭。所以这是我得到的输出:

Starting application
Total Duration { secs: 0, nanos: 808482 }

而不是像

这样的东西
Starting application
doing stuff 1
doing stuff 2
doing stuff 3
doing stuff 4
Total Duration { secs: 0, nanos: 808482 }

如果线程没有返回任何内容,如何使应用程序等待线程完成?

1 个答案:

答案 0 :(得分:3)

spawn函数返回JoinHandle。您可以收集向量中的所有句柄并在其上调用join

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();
    }
}