【发布时间】:2014-02-07 03:02:25
【问题描述】:
我曾多次尝试将内容传递给 spawn 函数(以创建新线程/任务)并让编译器告诉我 error: cannot capture variable of type "blah blah", which does not fulfill "Send", in a bounded closure。
有没有办法将类型转换为能够实现“发送”,或者是否根据某些规则固定?
例如,我可以使用这样的指令轻松实现ToStr trait:
#[deriving(ToStr, Rand)]
struct Point {
x: int,
y: int,
}
我可以为 Send 特征做类似的事情吗?还是“善良”的特质被区别对待?
这是一个关于这个问题的具体例子 - 有什么办法可以克服它吗?
fn create_process_options(cmdinfo: &CmdInfo) -> (ProcessOptions, Option<FileDesc>) {
// ... omitted
}
// "po" is of type std::run::ProcessOptions
let (po, filedesc_opt) = create_process_options(&cmdinfo);
spawn(proc() {
let mut ps = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
ps.finish();
});
编译器错误:
error: cannot capture variable of type `std::run::ProcessOptions<>`, which does not fulfill `Send`, in a bounded closure
let mut process = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
^~
note: this closure's environment must satisfy `Send`
let mut process = Process::new(cmdinfo.program, cmdinfo.args, po).expect("darn");
【问题讨论】:
-
这是因为
ProcessOptions<'a>的dir: Option<&'a Path>字段。包含引用的结构不能是Send。剩下的问题是为什么它是&Path而不是Path。答案似乎是std::io::process::ProcessConfig主要使用引用,包括可能来自ProcessOptions.dir的cwd: Option<&str>。 -
好的。感谢您的解释。我可以理解为什么要设置这些限制,但是在尝试进行多线程/任务编程时确实会使其成为地雷。
-
@quux00:实际上,我认为这将是 C++ 中的地雷(因为它有时会在你的脸上爆炸),而在 Rust 中,你得到的只是严厉地拒绝继续。跨度>
标签: rust