How to terminate or suspend a Rust thread from another thread?

后端 未结 3 1249
轮回少年
轮回少年 2020-12-08 16:14

Editor\'s note — this example was created before Rust 1.0 and the specific types have changed or been removed since then. The general questio

3条回答
  •  余生分开走
    2020-12-08 16:47

    The ideal solution would be a Condvar. You can use wait_timeout in the std::sync module, as pointed out by @Vladimir Matveev.

    This is the example from the documentation:

    use std::sync::{Arc, Mutex, Condvar};
    use std::thread;
    use std::time::Duration;
    
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair2 = pair.clone();
    
    thread::spawn(move|| {
        let &(ref lock, ref cvar) = &*pair2;
        let mut started = lock.lock().unwrap();
        *started = true;
        // We notify the condvar that the value has changed.
        cvar.notify_one();
    });
    
    // wait for the thread to start up
    let &(ref lock, ref cvar) = &*pair;
    let mut started = lock.lock().unwrap();
    // as long as the value inside the `Mutex` is false, we wait
    loop {
        let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
        // 10 milliseconds have passed, or maybe the value changed!
        started = result.0;
        if *started == true {
            // We received the notification and the value has been updated, we can leave.
            break
        }
    }
    

提交回复
热议问题