如何强制从文件中阻止读取的线程在Rust中恢复?

时间:2016-03-24 23:11:07

标签: rust blocking resume

因为Rust没有内置的以非阻塞方式从文件读取的能力,所以我必须生成一个读取文件/dev/input/fs0的线程以获取操纵杆事件。假设操纵杆未使用(无需读取),因此在读取文件时会阻止读取线程。

主线程是否有办法强制读取线程的阻塞读取恢复,因此读取线程可以干净地退出?

在其他语言中,我只是关闭主线程中的文件。这将强制阻止读取恢复。但是我还没有找到在Rust中这样做的方法,因为阅读需要对文件进行可变引用。

1 个答案:

答案 0 :(得分:1)

想法是仅在有可用数据时才调用File::read。如果没有可用数据,我们检查一个标志以查看主线程是否要求停止。如果没有,请再试一次。

以下是使用nonblock crate:

的示例
extern crate nonblock;

use std::fs::File;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use nonblock::NonBlockingReader;

fn main() {
    let f = File::open("/dev/stdin").expect("open failed");
    let mut reader = NonBlockingReader::from_fd(f).expect("from_fd failed");

    let exit = Arc::new(Mutex::new(false));
    let texit = exit.clone();

    println!("start reading, type something and enter");

    thread::spawn(move || {
        let mut buf: Vec<u8> = Vec::new();
        while !*texit.lock().unwrap() {
            let s = reader.read_available(&mut buf).expect("io error");
            if s == 0 {
                if reader.is_eof() {
                    println!("eof");
                    break;
                }
            } else {
                println!("read {:?}", buf);
                buf.clear();
            }
            thread::sleep(Duration::from_millis(200));
        }
        println!("stop reading");
    });

    thread::sleep(Duration::from_secs(5));

    println!("closing file");
    *exit.lock().unwrap() = true;

    thread::sleep(Duration::from_secs(2));
    println!("\"stop reading\" was printed before the main exit!");
}

fn read_async<F>(file: File, fun: F) -> thread::JoinHandle<()>
    where F: Send + 'static + Fn(&Vec<u8>)
{
    let mut reader = NonBlockingReader::from_fd(file).expect("from_fd failed");
    let mut buf: Vec<u8> = Vec::new();
    thread::spawn(move || {
        loop {
            let s = reader.read_available(&mut buf).expect("io error");
            if s == 0 {
                if reader.is_eof() {
                    break;
                }
            } else {
                fun(&buf);
                buf.clear();
            }
            thread::sleep(Duration::from_millis(100));
        }
    })
}

以下是使用poll crate nix绑定的示例。函数pool等待(超时)特定事件:

extern crate nix;

use std::io::Read;
use std::os::unix::io::AsRawFd;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use nix::poll;

fn main() {
    let mut f = std::fs::File::open("/dev/stdin").expect("open failed");
    let mut pfd = poll::PollFd {
        fd: f.as_raw_fd(),
        events: poll::POLLIN, // is there input data?
        revents: poll::EventFlags::empty(),
    };

    let exit = Arc::new(Mutex::new(false));
    let texit = exit.clone();

    println!("start reading, type something and enter");

    thread::spawn(move || {
        let timeout = 100; // millisecs
        let mut s = unsafe { std::slice::from_raw_parts_mut(&mut pfd, 1) };
        let mut buffer = [0u8; 10];
        loop {
            if poll::poll(&mut s, timeout).expect("poll failed") != 0 {
                let s = f.read(&mut buffer).expect("read failed");
                println!("read {:?}", &buffer[..s]);
            }
            if *texit.lock().unwrap() {
                break;
            }
        }
        println!("stop reading");
    });

    thread::sleep(Duration::from_secs(5));

    println!("closing file");
    *exit.lock().unwrap() = true;

    thread::sleep(Duration::from_secs(2));
    println!("\"stop reading\" was printed before the main exit!");

}