在不阻塞主线程的情况下读取 IO 的问题

问题描述 投票:0回答:0

我有这段代码在

impl App
内部运行,特别是在
fn launch()
内部运行,就像this example.

输出读取和写入必须在单独的线程中进行,这样 GUI 就不会死机。我已经尝试使用 MIO 和 tokio 以及子流程。对于普通线程,我在借用检查器方面遇到了问题,我太菜鸟了,无法解决。首先,这是程序的一个片段:

let mut child = Command::new(KOTLINC_PATH)
.arg("-script")
.arg(script_path)
.stdout(Stdio::piped())
// .stderr(Stdio::piped())
.spawn()
.expect("Could not execute script");

std::thread::spawn(move || {
    let out = BufReader::new(
        child.stdout.take().expect("Could not read from stdout."),
    );

    out.lines().for_each(|line| {
        self.output.terminals[0].append(line.unwrap().as_str());
        self.output.terminals[0].append("\n");
    });
});

这里是错误:

borrowed data escapes outside of associated function
`self` escapes the associated function body here
main.rs(281, 23): `self` is a reference that is only valid in the associated function body
main.rs(281, 19): lifetime `'a` defined here
borrowed data escapes outside of associated function
argument requires that `'a` must outlive `'static`

我读过一些关于使用 Arc> 的文章,但这需要更改函数签名,老实说,我也是一个菜鸟,无法弄清楚这一点。希望得到一些帮助。

更新

let mut child = Command::new(KOTLINC_PATH)
    .args(&["-script", script_path.clone().as_str()])
    .stdout(Stdio::piped())
    .spawn()
    .expect("Could not execute script");

let stdout = child.stdout.take().expect("Could not read from stdout.");

let output_clone = Arc::clone(&output);

let output_thread = thread::spawn(move || {
    let output_clone_ref = &output_clone; // Create a reference to the Arc<Mutex<String>> inside the closure

    for line in BufReader::new(stdout).lines() {
        let output_ref = output_clone_ref.lock().unwrap(); // Acquire a lock on the Mutex to modify the String

        (*output_ref).insert(line.unwrap().as_str());
        (*output_ref).insert("\n");
        drop(output_ref);
    }
});

// Gets stuck here.
output_thread.join().unwrap();
multithreading rust fltk
© www.soinside.com 2019 - 2024. All rights reserved.