使用迭代器实现 rayon `as_parallel_slice`

2024-05-12

我自己有一个小问题:

extern crate rayon;
use rayon::prelude::*;

#[derive(Debug)]
struct Pixel {
    r: Vec<i8>,
    g: Vec<i8>,
    b: Vec<i8>,
}

#[derive(Debug)]
struct Node{
    r: i8,
    g: i8,
    b: i8,
}

struct PixelIterator<'a> {
    pixel: &'a Pixel,
    index: usize,
}

impl<'a> IntoIterator for &'a Pixel {
    type Item = Node;
    type IntoIter = PixelIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        println!("Into &");
        PixelIterator { pixel: self, index: 0 }
    }
}

impl<'a> Iterator for PixelIterator<'a> {
    type Item = Node;
    fn next(&mut self) -> Option<Node> {
        println!("next &");
        let result = match self.index {
            0 | 1 | 2 | 3  => Node {
                r: self.pixel.r[self.index],
                g: self.pixel.g[self.index],
                b: self.pixel.b[self.index],
            },
            _ => return None,
        };
        self.index += 1;
        Some(result)
    }
}

impl ParallelSlice<Node> for Pixel {
    fn as_parallel_slice(&self) -> &[Node] {
        // ??
    }
}

fn main() {
    let p1 = Pixel {
        r: vec![11, 21, 31, 41],
        g: vec![12, 22, 32, 42],
        b: vec![13, 23, 33, 43],
    };

    p1.par_chunks(2).enumerate().for_each(|(index, chnk)| {
        for (cindex, i) in chnk.into_iter().enumerate(){
            println!("{:?}, {:?}", (index*2)+cindex, i);   
        }
    });
}

基本上我想用人造丝per_chunk功能,它要求我必须实现ParallelSlice特征。我想知道应该输入什么as_parallel_slice函数,以便我可以获得输出(顺序无关紧要):

0 Node { 11, 12, 13} 
1 Node { 21, 22, 23}
2 Node { 31, 32, 33}
3 Node { 41, 42, 43}

还有一个愚蠢的问题是as_parallel_slice限制 Trait 返回一个切片,根据我的理解,在这种情况下我需要事先获得完整的数据?由于我正在处理 DNA 序列(可能有很多数据),我想我应该转而使用 crossbeam 和迭代器,而不是通过人造丝进行基于切片的并行化,或者它们是更好的方法吗?


你不能创建一个切片Node除非你有一块连续的内存只包含Nodes。但你没有那个;来自每个的数据Node是从存储在三个独立的数据位中延迟复制的Vecs.

创建切片最明显的方法是首先创建所有Nodes in a Vec<Node>然后切一块。但是,我怀疑这正是您不想做的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用迭代器实现 rayon `as_parallel_slice` 的相关文章

随机推荐