I have a performance critical section of my rust code which I currently try to get faster with unsafe code. In this approach I grantee thread safety manually with barriers and separated index ranges for all threads in the vectors, so I do not want to compiler to check thread safety.
#[derive(Clone, Copy)]
struct CgPtrSet {
a: *const SparseMatrix,
b: *const DenseVector,
x: *mut DenseVector,
d: *mut DenseVector,
r: *mut DenseVector,
z: *mut DenseVector,
accuracy: *mut f64,
iterations: *mut usize,
}
fn cg_barrier_thread_worker(&self, ptrs: CgPtrSet, start: usize, end: usize) {
unsafe {
...
}
}
This works well while done in one thread:
self.cg_barrier_thread_worker(ptrs, start, end);
Now I run it in its own thread:
let thread_handle = thread::spawn(|| {
self.cg_barrier_thread_worker(ptrs, start, end);
});
thread_handle.join().unwrap();
That get me the compiler output:
error[E0277]: `*const sparse_matrix::SparseMatrix` cannot be shared between threads safely
error[E0277]: `*const dense_vector::DenseVector` cannot be shared between threads safely
...and so on for all members of CgPrtSet
I have tried to solve the issue using UnsafeCell with no success. How can I “convince” the compiler that I know my use of the object is thread save?