我有一个长时间运行的子进程,我需要读取和写入大量数据。我有一个读者线程和一个写作线程分别操纵child.stdout
和child.stdin
:
extern crate scoped_threadpool;
fn main() {
// run the subprocess
let mut child = std::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let child_stdout = child.stdout.as_mut().unwrap();
let child_stdin = std::sync::Mutex::new(child.stdin.as_mut().unwrap());
let mut pool = scoped_threadpool::Pool::new(2);
pool.scoped(|scope| {
// read all output from the subprocess
scope.execute(move || {
use std::io::BufRead;
let reader = std::io::BufReader::new(child_stdout);
for line in reader.lines() {
println!("{}", line.unwrap());
}
});
// write to the subprocess
scope.execute(move || {
for a in 0..1000 {
use std::io::Write;
writeln!(&mut child_stdin.lock().unwrap(), "{}", a).unwrap();
} // close child_stdin???
});
});
}
当编写完成后,我想关闭child_stdin
以便子进程完成并退出,以便读者看到EOF并返回pool.scoped
。我无法在child.wait()
之后执行此操作而无法调用child.wait()
,因为它是由两个线程借用的。
如何完成此计划?
答案 0 :(得分:2)
有趣的是,您通过使用Mutex
^ _ ^分享所有权来自行解决此问题。取代对child.stdin
的引用,取得对它的完全所有权并将其传递给线程。当线程结束时,它将被删除,隐式关闭它:
let mut child_stdin = child.stdin.unwrap();
// ...
scope.execute(move ||
for a in 0..1000 {
use std::io::Write;
writeln!(&mut child_stdin, "{}", a).unwrap();
}
// child_stdin has been moved into this closure and is now
// dropped, closing it.
);
如果您仍希望仍然可以致电wait
来获取ExitStatus
,请将引用更改为stdout
并转让stdin
的所有权使用Option::take
。这意味着child
根本没有借用:
let mut child = // ...
let child_stdout = child.stdout.as_mut().unwrap();
let mut child_stdin = child.stdin.take().unwrap();
// ...
child.wait().unwrap();