Skip to content

Instantly share code, notes, and snippets.

@blitzcode
Created March 5, 2016 13:18
Show Gist options
  • Save blitzcode/393c81115a32f7ac15e4 to your computer and use it in GitHub Desktop.
Save blitzcode/393c81115a32f7ac15e4 to your computer and use it in GitHub Desktop.
Rust parallel array
fn main() {
let data_in = (0..1000).collect::<Vec<i32>>();
let (_, mut data_in_slice) = data_in.split_at(0);
let mut data_out: Vec<i32> = Vec::with_capacity(data_in.len());
unsafe { data_out.set_len(data_in.len()); }
let (_, mut data_out_slice) = data_out.split_at_mut(0);
let nthreads = 5;
let threads: Vec<_> = (0..nthreads).map(|i| {
let range = data_in.len() as i32 / nthreads;
let seg_low = range * i;
let seg_high = if i == nthreads - 1 { data_in.len() as i32 } else { range * (i + 1) };
let seg_len = (seg_high - seg_low) as usize;
let (seg_in, new_data_in_slice) = data_in_slice.split_at(seg_len);
data_in_slice = new_data_in_slice;
let (seg_out, new_data_out_slice) = data_out_slice.split_at_mut(seg_len);
data_out_slice = new_data_out_slice;
thread::spawn(move || {
})
}).collect();
for thread in threads {
thread.join().unwrap();
}
}
fn main() {
let nthreads = 5;
let data_in = (0..1000).collect::<Vec<i32>>();
let data_in_chunks = data_in.chunks(data_in.len() / nthreads);
let mut data_out: Vec<i32> = Vec::with_capacity(data_in.len());
unsafe { data_out.set_len(data_in.len()); }
let data_out_chunks = data_out.chunks_mut(data_in.len() / nthreads);
let threads: Vec<_> = data_in_chunks.zip(data_out_chunks).map(|(cin, cout)| {
thread::spawn(move || {
for (i, num) in cin.iter().enumerate() {
cout[i] = *num;
}
})
}).collect();
for thread in threads {
thread.join().unwrap();
}
}
let mut vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
pool.scoped(|scoped| {
for e in &mut vec {
scoped.execute(move || {
*e += 1;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment