struct Slice<'a> {
index: usize,
data: &'a mut [i32]
}
fn block_slice(block: &mut [i32], slice_size: usize) -> Vec<Slice> {
let slice_num =
if block.len() % slice_size == 0 {
block.len() / slice_size
} else {
block.len() / slice_size + 1
};
if slice_num == 1 {
return vec![Slice { index: 0, data: block }];
}
let mut slices = Vec::with_capacity(slice_num);
let mut rest = block;
for index in 1..slice_num {
let (head, tail) = rest.split_at_mut(index * slice_size);
slices.push(Slice { index: index - 1, data: head });
if index == slice_num - 1 {
slices.push(Slice { index, data: tail });
} else {
rest = tail;
}
}
return slices;
}
大佬们好!
请问怎样可以对一个数组按大小切出多个可写的引用分片?(目的是准备把这些分片做并行修改)
上面的代码有问题,第 20 行的 rest 做了多次的写引用。
谢谢!
1
0Vincent0Zhang0 OP 已解决
'''rust let mut block = [0i32; BLOCK_SIZE]; let chunks: Vec<&mut [i32]> = block.chunks_mut(SLICE_SIZE).collect(); crossbeam::scope(|spwawner| { for (chunk_index, chunk) in chunks.into_iter().enumerate() { spwawner.spawn(move || { for index in 0..chunk.len() { chunk[index] += (index as i32).pow(2); } println!("Chunk[{:02}] completed!", chunk_index); }); } }); ''' 使用 chunks_mut 可以按大小分出可修改的切片,另外还需要 crossbeam 处理 block 在多线程时的生命周期问题。 |