gpt4 book ai didi

multithreading - 是否可以强制恢复休眠线程?

转载 作者:行者123 更新时间:2023-11-29 08:12:27 25 4
gpt4 key购买 nike

是否可以强制恢复已暂停的休眠线程?例如,通过调用 sleep:

std::thread::sleep(std::time::Duration::from_secs(60 * 20));

我知道我可以使用 std::sync::mpsc 在线程之间进行通信,但是如果线程处于休眠状态,这不会强制它在指示的时间之前唤醒。

我认为使用 std::sync::mpsc 也许Builder.name 与线程相关联,但不知道如何让线程唤醒。

最佳答案

如果您想被某个事件唤醒,thread::sleep()不是正确使用的功能,因为它不应该被停止。

在能够被事件唤醒的同时还有其他等待方法(这通常称为阻塞)。可能最简单的方法是将 channel 与 Receiver::recv_timeout() 一起使用 。通常发送 () 也足够了通过 channel 。这样我们只传递一个信号,但不发送实际数据。

如果您不想在特定超时后唤醒,但信号到达时,只需使用 Receiver::recv() .


超时示例:

use std::thread;
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;
use std::io;

fn main() {
let (sender, receiver) = mpsc::channel();

thread::spawn(move || {
loop {
match receiver.recv_timeout(Duration::from_secs(2)) {
Err(RecvTimeoutError::Timeout) => {
println!("Still waiting... I'm bored!");
// we'll try later...
}
Err(RecvTimeoutError::Disconnected) => {
// no point in waiting anymore :'(
break;
}
Ok(_) => {
println!("Finally got a signal! ♥♥♥");
// doing work now...
}
}
}
});

loop {
let mut s = String::new();
io::stdin().read_line(&mut s).expect("reading from stdin failed");
if s.trim() == "start" {
sender.send(()).unwrap();
}
}
}

在这里,第二个线程至少每两秒(超时)被唤醒一次,但一旦通过 channel 发送了一些东西也会更早。

关于multithreading - 是否可以强制恢复休眠线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43961436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com