Skip to content

Instantly share code, notes, and snippets.

@vks
Last active August 29, 2015 14:01
Show Gist options
  • Save vks/aeeb085b751ca2998eba to your computer and use it in GitHub Desktop.
Save vks/aeeb085b751ca2998eba to your computer and use it in GitHub Desktop.
How to parallelize elementwise vector addition
extern crate sync;
use sync::{Arc, Barrier};
/// Add two vectors elementwise.
/// This is parallelized by dividing them into chunks.
fn elementwise_add<T: Add<T, T> + Send>
(a: &Vec<T>, b: &Vec<T>, chunks: uint) -> Vec<T> {
assert_eq!(a.len(), b.len());
let size = a.len();
let chunksize = size / chunks;
assert!(chunksize != 0);
let barrier = Arc::new(Barrier::new(chunks + 1));
let mut c = Vec::<T>::with_capacity(size);
unsafe {
let a = a.as_ptr();
let b = b.as_ptr();
c.set_len(size);
let c = c.as_mut_ptr();
for i in range(0, chunks) {
let local_barrier = barrier.clone();
let begin = (i*chunksize) as int;
let end = ((i + 1)*chunksize) as int;
spawn(proc() {
for j in range(begin, end) {
*c.offset(j) = *a.offset(j) + *b.offset(j);
}
local_barrier.wait();
});
}
let begin = (chunks*chunksize) as int;
let end = size as int;
for j in range(begin, end) {
*c.offset(j) = *a.offset(j) + *b.offset(j);
}
}
barrier.wait();
c
}
fn main() {
let a: Vec<int> = range(0, 11).collect();
let b: Vec<int> = range(10, 21).collect();
let c = elementwise_add(&a, &b, 2);
println!("{}\n+\n{}", a, b);
println!("=\n{}", c);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment