简体   繁体   English

使用 Rust 定期唤醒另一个线程

[英]Wake another thread periodically with Rust

Condvar in Rust is good for waking another thread, but in this case below, I don't really need the true , I just want to wake the other thread periodically Rust 中的 Condvar 适合唤醒另一个线程,但在下面的这种情况下,我真的不需要true ,我只想定期唤醒另一个线程

use std::sync::{Arc, Mutex, Condvar};
use std::thread;
fn main() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair2 = Arc::clone(&pair);
    
    // Inside of our lock, spawn a new thread, and then wait for it to start.
    thread::spawn(move|| {
        let (lock, cvar) = &*pair2;
        let mut started = lock.lock().unwrap();
        // We notify the condvar that the value has changed.
        loop{
            *started = true;
            cvar.notify_one();
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
    });
    
    // Wait for the thread to start up.
    let (lock, cvar) = &*pair;
    let mut started = lock.lock().unwrap();
    loop {
        started = cvar.wait(started).unwrap();
        println!("done");
    }
    println!("end");
}

Also, this example does not even work, I don't know why.另外,这个例子甚至不起作用,我不知道为什么。 It should wake the main thread every 20 ms.它应该每 20 毫秒唤醒一次主线程。

The reason this doesn't work is that you're holding the mutex while you sleep.这不起作用的原因是你在睡觉时拿着互斥锁。 The main thread is only woken up after it has been hit with notify_one and its mutex is lockable.主线程只有在被notify_one命中并且它的互斥锁是可锁定的之后才会被唤醒。 But the spawned thread holds the mutex locked forever.但是生成的线程将互斥锁永远锁定。

Playground 操场

In fact, you don't need the lock at all in your spawned thread and you could make it contain no data by constructing it as Mutex::new(()) .实际上,您在生成的线程中根本不需要锁,您可以通过将其构造为Mutex::new(())使其不包含任何数据。 However, if you do that, it is possible that your main thread hasn't finished one loop by the time the spawned thread finishes its sleep.但是,如果您这样做,则在生成的线程完成睡眠时,您的主线程可能还没有完成一个loop The mutex ensures that when you call notify_one , the main thread is definitely waiting to be notified.互斥锁确保当您调用notify_one时,主线程肯定在等待通知。 If you want that behavior or not is up to you.是否想要这种行为取决于您。 With locking the mutex in the spawned thread, the main thread is woken up immediately if its previous loop took longer than one tick.在生成的线程中锁定互斥锁后,如果主线程的前一个循环花费的时间超过一个滴答声,则主线程会立即被唤醒。 Without the locking, wake-ups may be skipped and the next wake-up is aligned to the next tick.如果没有锁定,唤醒可能会被跳过,并且下一个唤醒与下一个刻度对齐。

But really, do what's in the answers @Finomnis suggested and use channels.但实际上,请按照@Finomnis 建议的答案执行操作并使用渠道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM