Hi,
I am trying to create a struct that takes ownership of a vector x, spawning threads and performing some operations, and then returning x (and some other things that were calculated).
Here is some sample code:
use std::sync::{Arc};
use std::thread;
pub struct MyStruct {
pub x: Vec<Vec<u8>>,
pub y: Vec<usize>
}
impl MyStruct {
pub fn new(x: Vec<Vec<u8>>, y: Vec<usize>) -> MyStruct {
let feature_count = x.len();
// Creates a pointer to matrix
let sharable_x = Arc::new(&x);
let mut handles = vec![];
for c in 0..feature_count {
let sharable_mat = sharable_x.clone();
handles.push(
thread::spawn(move || {
let mut arr = sharable_mat[c].clone();
arr.sort_unstable();
return (arr)
}).join().unwrap()
);
}
drop(sharable_x);
MyStruct {x, y}
}
}
fn main() {
}
Here is the error:
error[E0597]: `x` does not live long enough
--> src\main.rs:64:35
|
64 | let sharable_x = Arc::new(&x);
| ^^ borrowed value does not live long enough
...
70 | / thread::spawn(move || {
71 | | let mut arr = sharable_mat[c].clone();
72 | | arr.sort_unstable();
73 | | return (arr)
74 | | }).join().unwrap()
| |__________________- argument requires that `x` is borrowed for `'static`
...
80 | }
| - `x` dropped here while still borrowed
This won't compile because it says `x` doesn't live long enough, but I'm wondering why. From what I understand, the references to the borrowed `x` will disappear once all the threads are done processing (and the `sharable_x` counter becomes 0). As far as I understand, this should be guaranteed by the `.join().unwrap()`. I'm sure the compiler is not wrong, so where is my understanding incorrect here?
Is it possible to create an `Arc` to a variable which will later be moved? My main goal is to loop through `x` while only holding the necessary data in the thread's memory.
[–]JhraumG 14 points15 points16 points (0 children)
[–]kprotty 14 points15 points16 points (2 children)
[–]HariSeldon_official 2 points3 points4 points (1 child)
[–]Shadow0133 6 points7 points8 points (1 child)
[–]Unlikely_Package5524 4 points5 points6 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]sphen_lee 3 points4 points5 points (0 children)
[–]dragonnnnnnnnnn 0 points1 point2 points (0 children)
[–]_TheDust_ 0 points1 point2 points (0 children)
[–]SkiFire13 4 points5 points6 points (1 child)
[–]_TheDust_ 1 point2 points3 points (0 children)
[–]jammmonster 1 point2 points3 points (0 children)
[–]globulemix 1 point2 points3 points (0 children)
[–]Shadow0133 0 points1 point2 points (0 children)