I've been working on a function that will copy a bunch of files from a source to a destination using Rust and threads. I'm getting some trouble making the threads share the iterator. I am not still used to the borrowing system:
extern crate libc; extern crate num_cpus; use libc::{c_char, size_t}; use std::thread; use std::fs::copy; fn python_str_array_2_str_vec<T, U, V>(_: T, _: U) -> V { unimplemented!() } #[no_mangle] pub extern "C" fn copyFiles( sources: *const *const c_char, destinies: *const *const c_char, array_len: size_t, ) { let src: Vec<&str> = python_str_array_2_str_vec(sources, array_len); let dst: Vec<&str> = python_str_array_2_str_vec(destinies, array_len); let mut iter = src.iter().zip(dst); let num_threads = num_cpus::get(); let threads = (0..num_threads).map(|_| { thread::spawn(|| while let Some((s, d)) = iter.next() { copy(s, d); }) }); for t in threads { t.join(); } } fn main() {}
I'm getting this compilation error that I have not been able to solve:
error[E0597]: `src` does not live long enough --> src/main.rs:20:20 | 20 | let mut iter = src.iter().zip(dst); | ^^^ does not live long enough ... 30 | } | - borrowed value only lives until here | = note: borrowed value must be valid for the static lifetime... error[E0373]: closure may outlive the current function, but it borrows `**iter`, which is owned by the current function --> src/main.rs:23:23 | 23 | thread::spawn(|| while let Some((s, d)) = iter.next() { | ^^ ---- `**iter` is borrowed here | | | may outlive borrowed value `**iter` | help: to force the closure to take ownership of `**iter` (and any other referenced variables), use the `move` keyword, as shown: | thread::spawn(move || while let Some((s, d)) = iter.next() {
I've seen the following questions already:
Value does not live long enough when using multiple threads I'm not using chunks
, I would like to try to share an iterator through the threads although creating chunks to pass them to the threads will be the classic solution.
Unable to send a &str between threads because it does not live long enough I've seen some of the answers to use channels to communicate with the threads, but I'm not quite sure about using them. There should be an easier way of sharing just one object through threads.
Why doesn't a local variable live long enough for thread::scoped This got my attention, scoped
is supposed to fix my error, but since it is in the unstable channel I would like to see if there is another way of doing it just using spawn
.
Can someone explain how should I fix the lifetimes so the iterator can be accessed from the threads?