I'm trying to map a 2d slice in parallel. I'm doing this by assigning every child slice to one thread. So, if the slice is 10x10, 10 threads will be spawned.
I'm doing this by creating a Mutex for each child slice. The problem is that I'm getting an error for the parent slice:
error[E0759]: `collection` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src\lib.rs:151:34
|
145 | fn gen_map_par<T: Send + Sync, F: Fn(f32, &mut T) + Send + Sync + 'static>(&self, collection: &[&[T]], predicate: F) {
| ------- this data with an anonymous lifetime `'_`...
...
151 | for (x, i) in collection.iter().enumerate() {
| ^^^^ ...is captured here...
...
155 | let handle = thread::spawn(move || {
| ------------- ...and is required to live as long as `'static` here
For more information about this error, try `rustc --explain E0759`.
The error shows that collection is being captured. Here is the associated code.
fn gen_map_par<T: Send + Sync, F: Fn(f32, &mut T) + Send + Sync + 'static>(
&self,
collection: &[&[T]],
predicate: F,
) {
let perm = Arc::new(self.perm);
let closure = Arc::new(predicate);
let mut handles = Vec::new();
for (x, i) in collection.iter().enumerate() {
// iterating through parent slice
let p = Arc::clone(&perm);
let c = Arc::clone(&closure);
let s = Arc::new(Mutex::new(*i)); // mutex created for one entire child slice
let handle = thread::spawn(move || {
// spawning the thread
let slice = s.lock().unwrap();
// collection gets moved into the thread for some reason.
for (y, e) in slice.iter().enumerate() {
let v = Simplex::convert_range(
max_2d,
min_2d,
1.0,
-1.0,
generate2d(x as f32, y as f32, &p),
);
(c)(v, &mut slice[y]);
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
I've tried wrapping the 'collection' in an arc/mutex, but neither of these works. I'm not sure how to solve this problem. The only solution I've found is to make collection
static, but this would require the user to input a static variable, which I do not want to require.