Rust 使用channel实现线程超时

如果线程超过一定时间没有send,接收者就会报一个TimeOut异常,这样主线程就能知道子线程超时了。

use crossbeam::channel::bounded;

use std::thread;
use std::time::Duration;

fn main() {
    let (s, r) = bounded(0);
    thread::spawn(move || {
        thread::sleep(Duration::from_secs(3));//假设线程使用了3秒
        s.send(());
    });
    //2秒超时
    if let Ok(msg) = r.recv_timeout(Duration::from_secs(2)) {
        println!("Hello, world!");
    }else {
        println!("Time out");
    };

}
tag(s): rust channel 
show comments · back · home