我有一个长时间运行的子进程,我需要读取和写入大量数据。我有一个读取器线程和一个写入器线程来操纵child.stdout
and 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()
因为它被两个线程借用。
我怎样才能完成这个程序?
有趣的是,您自己通过使用共享所有权造成了这种情况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
to use 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)