gpt4 book ai didi

rust - 如何从 Pin>> 中获取 Pin<&mut T>

转载 作者:行者123 更新时间:2023-12-03 11:31:07 30 4
gpt4 key购买 nike

我正在编写一个需要共享流所有权的流适配器。

将流(私下)存储在 Pin<Arc<Mutex<impl Stream>>> 中是否正确? ?

如何调用poll_next(self: Pin<&mut Stream>在流?

最佳答案

Mutex没有所谓的结构钉扎,这在 std::pin 中有描述。模块文档:

It turns out that it is actually up to the author of the data structure to decide whether the pinned projection for a particular field turns Pin<&mut Struct> into Pin<&mut Field> or &mut Field. [...] As the author of a data structure you get to decide for each field whether pinning "propagates" to this field or not. Pinning that propagates is also called "structural", because it follows the structure of the type.


Mutex<T>没有结构固定,因为结构( Mutex )的固定不会传播到字段( T ) - 获得未固定的 &mut T 是安全的来自 Pin<&mut Mutex<T>> (即,通过使用 Deref 而不是 DerefMut 并锁定互斥锁),即使 TMutex<T>!Unpin .

为了转这个 &mut T变成 Pin<&mut T> ,你必须做另一层未经检查的保证,使用 unsafePin::new_unchecked , 来证明 T本身永远不会移动。这似乎违背了“外部”的目的 Pin .

根据您的数据结构允许的内容,您可能会考虑以下选项之一:
  • Arc<Mutex> 编写包装器固定 Mutex 的内容通过 Pin 访问时(您无法实现 Deref ,但您可以编写返回 MutexGuard 并在内部执行 Pin -wrapping 的方法)
  • 简单地将共享可变性插入实现 Stream 的类型中,如果你的数据结构允许的话。
  • 关于rust - 如何从 Pin<Arc<Mutex<T>>> 中获取 Pin<&mut T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60248333/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com