英文:
Why is &mut Send? How can a thread capture a &mut in safe Rust?
问题
"Sync"特性的语言说明如下:
仅当
T
是Send
时,&mut T
才是Send
有人能提供一个代码示例,说明这实际上是相关的吗?
thread::spawn
要求其闭包借用'static
寿命,因此只有静态变量可以由线程闭包借用,但安全的Rust不允许static mut
。因此,在线程闭包中不应该有任何方式可以通过&mut
捕获任何内容。
在哪种情况下,&mut
的Send
能力才会有关?
英文:
The language docs state:
> &mut T
is Send
if and only if T
is Send
Can somebody provide a code example of where this is actually relevant?
thread::spawn
requires its closure to borrow for 'static
lifetime, therefore only statics can be borrowed by a thread closure, but safe Rust doesn't allow static mut
. Thus, it should not be possible to capture anything in a thread-closure by &mut
anyway.
In which use-case can a &mut
's Send
-ability be of relevance?
答案1
得分: 5
&mut T
应该在原则上是 Send
的(如果 T
是 Send
);不应该仅仅因为你无法构建一个安全的用例而忽略实现它(unsafe
存在是有原因的)。
但是存在安全的用例:
-
std::thread::scope
提供了一种在其他线程中执行代码并允许访问本地变量的方法。在链接的文档中,另一个线程中使用了&mut i32
,因此需要Send
。 -
使用
&'static mut T
并不是unsafe
的,而且static mut
不是创建它的唯一方式。例如,可以使用Box::leak
安全地完成这个操作。这显然应该适用于发送到另一个线程。 -
async
任务可能希望在跨越.await
点时保持Send
,因此需要&mut T
来实现Send
。当编写async
函数时,无论你是否意识到,这都很容易做到。
英文:
A &mut T
should be Send
on principle (if T
is Send
); the implementation shouldn't be disregard simply because you can't construct a safe use-case for it (unsafe
still exists for a reason).
But there are safe use-cases:
-
std::thread::scope
provides a way to execute code in other threads while allowing access to local variables. In the linked documentation a&mut i32
is used in another thread, and thus requiresSend
. -
It is not
unsafe
to use a&'static mut T
andstatic mut
is not the only way to create one. It can be done safely by usingBox::leak
for example. This should clearly be viable for sending to another thread. -
async
tasks may want to beSend
while keeping internal mutable references across.await
points, and thus require&mut T
to implementSend
. This is trivially done all the time whether you realize it or not when writingasync
functions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论