0

I am trying to take a vec and process it's content in parallel using multiple threads.

The code I came up with is similar to this:

use std::thread;

fn main() {
    let numbers = vec![1,2,3,4];
    let res = numbers.chunks(2).map(|chunk| {

        let joinhandler = thread::spawn(move || {
            chunk.iter().map(|x| x * 2).collect::<Vec<u8>>()
        });
        joinhandler.join().unwrap()
    }).flatten().collect::<Vec<u8>>();

    println!("{:?}", res);
}

But this fail with the following error:

error[E0597]: `numbers` does not live long enough
  --> src/main.rs:5:15
   |
5  |       let res = numbers.chunks(2).map(|chunk| {
   |                 ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
6  |
7  |           let joinhandler = thread::spawn(move || {
   |  ___________________________-
8  | |             chunk.iter().map(|x| x * 2).collect::<Vec<u8>>()
9  | |         });
   | |__________- argument requires that `numbers` is borrowed for `'static`
...
14 |   }
   |   - `numbers` dropped here while still borrowed

for the life of me, I cannot figure out how to make the borrow checker happy in this case.

PS: I know there are other approaches to processing a vec with multiple threads. This is not a question about finding other approach. This is a question about why this particular approach is not compiling and how to fix it if possible.

Finlay Weber
  • 2,989
  • 3
  • 17
  • 37

0 Answers0