提问人:Orcadeum 提问时间:3/26/2023 最后编辑:cafce25Orcadeum 更新时间:3/26/2023 访问量:97
在不阻塞主线程的情况下读取 IO 时出现的问题
Problems with reading IO without blocking main thread
问:
我有这段代码,它在内部运行,特别是在内部运行,就像这个例子一样。impl App
fn launch()
输出读取和写入必须在单独的线程中进行,以便 GUI 不会冻结。我有 treid 来使用 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<Mutex 的文章<...>>但这需要更改函数签名,老实说,我也太菜鸟了,无法弄清楚这一点。将不胜感激。
更新
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();
答: 暂无答案
评论
self.output.terminals[0]
Arc<Mutex<…>>
std::sync::mpsc::channel
output_clone
output_clone
Arc<Mutex<String>>
Copy
join