MRE:
use std::sync::Arc;
use std::thread;
fn main() {
let arr1 = Arc::new(vec![10; 100]);
let arr2 = Arc::new(vec![20; 100]);
let arr3 = Arc::new(vec![00; 100]); // Going to need interior mutability. Might need to use
// Mutex/RwLock. Need to find a way to lock a slice instead
// of the entire structure.
let mut handles = vec![];
for i in 0..4 {
let chunk_beg = 25 * i;
let chunk_end = chunk_beg + 25;
let arr1_clone = Arc::clone(&arr1);
let arr2_clone = Arc::clone(&arr2);
let arr3_clone = Arc::clone(&arr3);
handles.push(thread::spawn(move || {
for idx in chunk_beg..chunk_end {
arr3_clone[idx] = arr1_clone[idx] + arr2_clone[idx];
}
}));
}
for handle in handles {
handle.join();
}
}
Error:
error[E0596]: cannot borrow data in an `Arc` as mutable
--> src/main.rs:23:17
|
23 | arr3_clone[idx] = arr1_clone[idx] + arr2_clone[idx];
| ^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<Vec<i32>>`
What I am trying not to do: Lock arr3_clone in its entirety because at that point, the threads just become sequential.
What I am trying to do: Find a way to write into individual slices of arr3_clone indirections.
rayon
. If you want to do it manually, you can usesplit_at_mut
to get independent mutable references to each chunk, and scoped threads so that you can capture plain references in your threads.!Sync
. Atomic integers,Mutex
, andRwLock
all provide thread-safe (and thereforeSync
) interior mutability.