Unsafe multi-threaded buffer output
Published 410d ago
ayebear
See C++ version: https://gist.github.com/ayebear/7ee6c64c387413a90532da8f838f32d6 Both rust and c++ versions seem to work.
use rayon::prelude::*;
// source: https://stackoverflow.com/a/64502824
struct EvilPtr<T> {
ptr: *mut T,
}
impl<T> EvilPtr<T> {
fn new(inp: &mut T) -> Self {
EvilPtr { ptr: inp as *mut T }
}
unsafe fn deref(&self) -> *mut T {
self.ptr
}
}
unsafe impl<T> Sync for EvilPtr<T> {}
unsafe impl<T> Send for EvilPtr<T> {}
fn main() {
const COUNT: usize = 1000;
let mut arr: Vec<i32> = (0..COUNT as i32).collect();
let e = EvilPtr::new(&mut arr[0]);
unsafe {
(0..COUNT).into_par_iter().for_each(|x| {
*e.deref().add(x) = x as i32;
});
}
println!("{:?}", arr);
}
Please login or sign up to comment and collaborate