gpt4 book ai didi

vector - 有没有办法将 ChunkMut 从 Vec::chunks_mut 转换为切片 &mut [T]?

转载 作者:行者123 更新时间:2023-11-29 08:32:02 25 4
gpt4 key购买 nike

我正在并行填充一个向量,但对于这个一般性问题,我只找到了提示,没有找到答案。

下面的代码有效,但我想切换到 Rng::fill 而不是遍历每个 block 。可能无法在单个 Vec 中包含多个可变切片;我不知道。

extern crate rayon;
extern crate rand;
extern crate rand_xoshiro;

use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256StarStar;
use rayon::prelude::*;
use std::{iter, env};
use std::sync::{Arc, Mutex};

// i16 because I was filling up my RAM for large tests...
fn gen_rand_vec(data: &mut [i16]) {
let num_threads = rayon::current_num_threads();
let mut rng = rand::thread_rng();
let mut prng = Xoshiro256StarStar::from_rng(&mut rng).unwrap();
// lazy iterator of fast, unique RNGs
// Arc and Mutex are just so it can be accessed from multiple threads
let rng_it = Arc::new(Mutex::new(iter::repeat(()).map(|()| {
let new_prng = prng.clone();
prng.jump();
new_prng
})));
// generates random numbers for each chunk in parallel
// par_chunks_mut is parallel version of chunks_mut
data.par_chunks_mut(data.len() / num_threads).for_each(|chunk| {
// I used extra braces because it might be required to unlock Mutex.
// Not sure.
let mut prng = { rng_it.lock().unwrap().next().unwrap() };
for i in chunk.iter_mut() {
*i = prng.gen_range(-1024, 1024);
}
});
}

最佳答案

事实证明,一个 ChunksMut 迭代器给出切片。我不确定如何从文档中收集到这些内容。我通过阅读弄明白了 the source :

#[derive(Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct ChunksMut<'a, T:'a> {
v: &'a mut [T],
chunk_size: usize
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> Iterator for ChunksMut<'a, T> {
type Item = &'a mut [T];

#[inline]
fn next(&mut self) -> Option<&'a mut [T]> {
if self.v.is_empty() {
None
} else {
let sz = cmp::min(self.v.len(), self.chunk_size);
let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.split_at_mut(sz);
self.v = tail;
Some(head)
}
}

我想这只是经验;对其他人来说,很明显 ChunksMut<T> 类型的迭代器来自 Vec<T>返回 [T] 类型的对象.现在说得通了。只是中间结构不是很清楚。

pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<T>
// ...
impl<'a, T> Iterator for ChunksMut<'a, T>

读到这里,看起来迭代器返回了 T 类型的对象, 与 Vec<T>.iter() 相同,这是没有意义的。

关于vector - 有没有办法将 ChunkMut<T> 从 Vec::chunks_mut 转换为切片 &mut [T]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848732/

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