这是我多次遇到过的问题。
您有需要转到任务的数据。
您希望安全地将数据发送到任务并远程处理。
......等待结果如何。
像这样的围栏:http://is.gd/fnhRta
use std::thread::Thread;
#[derive(Debug)]
struct Foo<'a> {
fp: &'a u32
}
impl<'a> Foo<'a> {
fn new(v:&'a u32) -> Foo<'a> {
return Foo {
fp: v
};
}
}
fn main() {
let value = 100;
let foo = Foo::new(&value);
let guard = Thread::scoped(|| {
println!("{:?}", foo);
});
// We know foo is valid in the remote thread, because guard is in the same
// scope of foo... but how do we express that using lifetimes?
guard.join();
}
是否可以使用生命周期来表达这一点?
本质上只接受Foo&lt; a&gt;的东西。其中&lt;'a&gt;是&lt; =当前{ ... }
块的生命周期。
答案 0 :(得分:0)
您编写的代码现在有效:
use std::thread;
#[derive(Debug)]
struct Foo<'a> {
fp: &'a u32
}
impl<'a> Foo<'a> {
fn new(v: &'a u32) -> Foo<'a> {
Foo { fp: v }
}
}
fn main() {
let value = 100;
let foo = Foo::new(&value);
let guard = thread::scoped(|| {
println!("{:?}", foo);
});
// We know foo is valid in the remote thread, because guard is in the same
// scope of foo... but how do we express that using lifetimes?
guard.join();
}
这可能是由RFC 458造成的,这放宽了对Send
/ Sync
的限制。现在,thread::scoped
返回JoinGuard
,其生命周期与闭包相同。