What is the standard way to get a Rust thread out of blocking operations?

China☆狼群 提交于 2019-11-29 11:21:12

There is no such thing. Blocking means blocking.

Instead, you deliberately use tools that are non-blocking. That's where libraries like mio or futures come in — they handle the architecture of sticking all of this non-blocking, asynchronous pieces together.

catch (InterruptedException e)

Rust doesn't have exceptions. If you expect to handle a failure case, that's better represented with a Result.

Thread.interrupt()

This doesn't actually do anything beyond setting a flag in the thread that some code may check and then throw an exception for. You could build the same structure yourself. One simple implementation:

use std::{
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    thread,
    time::Duration,
};

fn main() {
    let please_stop = Arc::new(AtomicBool::new(false));

    let t = thread::spawn({
        let should_i_stop = please_stop.clone();
        move || {
            while !should_i_stop.load(Ordering::SeqCst) {
                thread::sleep(Duration::from_millis(100));
                println!("Sleeping");
            }
        }
    });

    thread::sleep(Duration::from_secs(1));
    please_stop.store(true, Ordering::SeqCst);
    t.join().unwrap();
}

Sleep

No way of interrupting, as far as I know. The documentation even says:

On Unix platforms this function will not return early due to a signal

Socket IO

You put the socket into nonblocking mode using methods like set_nonblocking and then handle ErrorKind::WouldBlock.

File IO

There isn't really a good cross-platform way of performing asynchronous file IO. Most implementations spin up a thread pool and perform blocking operations there, sending the data over something that does non-blocking.

Queue IO

Perhaps you mean something like a MPSC channel, in which case you'd use tools like try_recv.

See also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!