rust 我怎样才能使一个可变迭代器锁定内部数据,直到删除?

jslywgbw  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(118)

我的目标是使用many_iter_mut()方法创建一个NewType(Arc<RwLock<Vec<T>>>),该方法返回一个迭代器,该迭代器在内部Vec<T>上持有一个写锁(RwLockWriteGuard)。
因此,写锁将由ManyIterMut迭代器持有,直到迭代器被删除。这与每次调用ManyIterMut::next()都获得写锁不同。(我已经在其他地方工作了)
这对于使调用者能够同时设置多个元素和读取多个元素非常有用,但原子地。因此,从一批写入到下一批写入,读取器将始终看到一致的视图。(我以前的ManyIterMut实现失败了并发测试。)
问题是由于生存期问题,我无法编译ManyIterMut::next()方法。编译器似乎不喜欢write_lockManyIterMut拥有,而不是被迭代的LockedVec拥有。
这是playground
生成错误的代码是:

impl<'a, V, T: 'a> LendingIterator for ManyIterMut<'a, V, T>
where
    V: StorageVecWrites<T> + ?Sized,
    V::LockedData: StorageVecReads<T>,
    T: Copy,
{
    type Item<'b> = StorageSetter<'b, V, T>
    where
        Self: 'b;

    // This is the fn that won't compile.
    //
    // we can't change the fn signature, it is defined by lending_iterator::LendingIterator trait.
    fn next(&mut self) -> Option<Self::Item<'_>> {
        if let Some(i) = Iterator::next(&mut self.indices) {
            let value = self.write_lock.get_at(i).unwrap();
            Some(StorageSetter {
                phantom: Default::default(),
                write_lock: &mut self.write_lock,  // <--- this seems to be the problem.  Because it has &mut self lifetime, not Self::Item<'_> lifetime
                index: i,
                value,
            })
        } else {
            None
        }
    }
}

字符串
错误是:

error: lifetime may not live long enough
   --> src/main.rs:164:13
    |
148 |   impl<'a, V, T: 'a> LendingIterator for ManyIterMut<'a, V, T>
    |        -- lifetime `'a` defined here
...
161 |       fn next(&mut self) -> Option<Self::Item<'_>> {
    |               - let's call the lifetime of this reference `'1`
...
164 | /             Some(StorageSetter {
165 | |                 phantom: Default::default(),
166 | |                 write_lock: &mut self.write_lock,  // <--- this seems to be the problem.  Because it has &mut self lifetime, not Self::It...
167 | |                 index: i,
168 | |                 value,
169 | |             })
    | |______________^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
    |
    = note: requirement occurs because of the type `StorageSetter<'_, V, T>`, which makes the generic argument `'_` invariant
    = note: the struct `StorageSetter<'c, V, T>` is invariant over the parameter `'c`
    = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance

error: could not compile `playground` (bin "playground") due to previous error


那么,我错过了什么?这似乎是可能的。或者有一个更简单的方法?

0sgqnhkj

0sgqnhkj1#

write_lock: &'c mut RwLockWriteGuard<'c, V::LockedData>,

字符串
这个模式(&'a mut T<'a>)(几乎?)总是错误的。At允许使用数据 * 最多 * 一次。更多信息请参见Borrowing something forever
解决方案是引入另一个生命周期。这需要一些修正,主要是在type Item<'b> = StorageSetter<'b, V, T>中将其更改为type Item<'b> = StorageSetter<'a, 'b, V, T>

相关问题