Skip to content

Instantly share code, notes, and snippets.

@ugovaretto
Forked from sitag/parallel_op_vec.rs
Created April 9, 2022 02:19
Show Gist options
  • Save ugovaretto/35645779a7a197fc1b6c88c0a0cd3a50 to your computer and use it in GitHub Desktop.
Save ugovaretto/35645779a7a197fc1b6c88c0a0cd3a50 to your computer and use it in GitHub Desktop.
[rust] operating on a vector in parallel with unsafe rust
#![feature(unique)]
use std::thread::spawn;
// operating on a vector in parallel
fn main() {
let mut data:Vec<u32> = vec![1u32, 2, 3];
println!("{:?}", data);
let head = data.as_mut_ptr();
let mut guards = (0..3).map(|i|
unsafe {
let mut target = std::ptr::Unique::new(head.offset(i));
let guard = spawn(move || {
std::ptr::write(target.get_mut(), 10 + i as u32);
});
guard
});
if guards.all(|guard| match guard.join() { Ok(_) => true, Err(_) => false }) {
println!("{:?}", data);
} else {
println!("__COULD_NOT_JOIN_ALL__");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment