英文:
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::scopeprovides a way to execute code in other threads while allowing access to local variables. In the linked documentation a&mut i32is used in another thread, and thus requiresSend. -
It is not
unsafeto use a&'static mut Tandstatic mutis not the only way to create one. It can be done safely by usingBox::leakfor example. This should clearly be viable for sending to another thread. -
asynctasks may want to beSendwhile keeping internal mutable references across.awaitpoints, and thus require&mut Tto implementSend. This is trivially done all the time whether you realize it or not when writingasyncfunctions.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论