这是怎么回事?
thread::spawn
再一次:
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static, // <-- this line is important for us
T: Send + 'static,
Foo
包含
Arc<Receiver<_>>
,让我们检查一下
Arc
implements
Send
:
impl<T> Send for Arc<T>
where
T: Send + Sync + ?Sized,
所以呢
Arc<T>
工具
如果
T
工具
和
Sync
Receiver
implements
Send
,
it does
not
implement
Sync
.
那为什么呢
有如此强烈的要求
T
发送
弧
可以像容器一样工作;如果你能隐藏一些无法实现的东西
弧
,将它发送到另一个线程并在那里解包。。。坏事就会发生。有趣的是要知道原因
也必须实施
同步
,这显然也是你正在努力解决的问题:
编译器不能知道
弧
在里面
福
#[derive(Clone)]
到
稍后(这是可能的,没有问题):
fn main() {
let (example, sender) = Foo::new();
let clone = example.clone();
let handle = example.run_thread();
clone.run();
// oopsie, now the same `Receiver` is used from two threads!
handle.join();
}
接收器
在线程之间共享。这不好,因为
接收器
不执行
!
对我来说,这个代码提出了一个问题:为什么
弧
弧
福
是唯一的所有者
. 如果你“不想分享(接收者)”,那么拥有多个所有者是没有意义的。