为什么是 `&mut Send`?线程如何在安全的Rust中捕获 `&mut`?

huangapple go评论99阅读模式
英文:

Why is &mut Send? How can a thread capture a &mut in safe Rust?

问题

"Sync"特性的语言说明如下:

仅当TSend时,&mut T才是Send

有人能提供一个代码示例,说明这实际上是相关的吗?
thread::spawn要求其闭包借用'static寿命,因此只有静态变量可以由线程闭包借用,但安全的Rust不允许static mut。因此,在线程闭包中不应该有任何方式可以通过&mut捕获任何内容。

在哪种情况下,&mutSend能力才会有关?

英文:

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 的(如果 TSend);不应该仅仅因为你无法构建一个安全的用例而忽略实现它(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 requires Send.

  • It is not unsafe to use a &'static mut T and static mut is not the only way to create one. It can be done safely by using Box::leak for example. This should clearly be viable for sending to another thread.

  • async tasks may want to be Send while keeping internal mutable references across .await points, and thus require &mut T to implement Send. This is trivially done all the time whether you realize it or not when writing async functions.

huangapple
  • 本文由 发表于 2023年7月18日 01:54:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定