How to check if a thread has finished in Rust?

前端 未结 4 908
情书的邮戳
情书的邮戳 2020-12-18 19:18

When I spawn a thread in Rust, I get a JoinHandle, which is good for... joining (a blocking operation), and not much else. How can I check if a ch

4条回答
  •  既然无缘
    2020-12-18 19:41

    It's possible, friends. Use refcounters which Rust will drop on end or panic. 100% safe. Example:

    use std::time::Duration;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::thread;
    
    fn main() {
        // Play with this flag
        let fatal_flag = true;
        let do_stop = true;
    
        let working = Arc::new(AtomicBool::new(true));
        let control = Arc::downgrade(&working);
    
        thread::spawn(move || {
            while (*working).load(Ordering::Relaxed) {
                if fatal_flag {
                    panic!("Oh, my God!");
                } else {
                    thread::sleep(Duration::from_millis(20));
                    println!("I'm alive!");
                }
            }
        });
    
        thread::sleep(Duration::from_millis(50));
    
        // To stop thread
        if do_stop {
            match control.upgrade() {
                Some(working) => (*working).store(false, Ordering::Relaxed),
                None => println!("Sorry, but thread died already."),
            }
        }
    
        thread::sleep(Duration::from_millis(50));
    
        // To check it's alive / died
        match control.upgrade() {
            Some(_) => println!("Thread alive!"),
            None => println!("Thread ends!"),
        }
    }
    

    Gist: https://gist.github.com/DenisKolodin/edea80f2f5becb86f718c330219178e2

    At playground: https://play.rust-lang.org/?gist=9a0cf161ba0bbffe3824b9db4308e1fb&version=stable&backtrace=0

    UPD: I've created thread-control crate which implements this approach: https://github.com/DenisKolodin/thread-control

提交回复
热议问题