No static lifetime for thread

n the code below, I had to add the 'static lifetime to the input parameter, in order to get rid of this error:
pub fn get_feq(input: &[&str], worker_count: usize) -> HashMap<char, usize> {
let n_elements = input.len() / worker_count;

let handles: Vec<_> = (0..worker_count)
    .map(|i| {
        thread::spawn(move || {
            let start = i * n_elements;
            let end = if i < worker_count - 1 {
                (i + 1) * n_elements
            } else {
                input.len()
            };
            let local_input = &input[start..end];
            let mut local_hashmap = HashMap::new();

            for s in local_input {
                for c in s.chars() {
                    *local_hashmap.entry(c).or_insert(0) += 1;
                }
            }

            local_hashmap
        })
    })
    .collect();

let mut freq_map = HashMap::new();

for handle in handles {
    let local_hashmap = handle.join().unwrap();
    for (c, count) in local_hashmap {
        *freq_map.entry(c).or_insert(0) += count;
    }
}

println!("{:#?}", freq_map);

return freq_map;

}
how i can solve this without using crossbeam.

There's no safe way for the spawned threads to access input without using a scoped-thread implementation. This can be crossbeam_utils::thread::scope(), rayon::scope(), scoped_threadpool::Pool::scoped(), yastl::Pool::scoped(), poolite::Pool::scoped(), easy_parallel::Parallel, or any of the other myriad implementations. Alternatively, if you're using nightly Rust, you can use the unstable std::thread::scope() function.

6 Likes

Thanks.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.