Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust threadpool crate how to execute on iterator?

Cargo.toml

threadpool = "1.8.1"

I am using threadpool crate, just for learning purposes, if there are some better threadpool crates please inform me.

Code with problem, simplified version:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use threadpool::ThreadPool;

fn main() {
    let pool = ThreadPool::new(4);
    let v2 = vec!["a".to_string(), "b".to_string(), "c".to_string(), ];
     
    for i in v2.iter() { // .iter() is the problem
        pool.execute(move || println!("{}", i));
    }
    
    pool.join();
}

Error:

error[E0597]: `v2` does not live long enough
for i in v2.iter() { // .iter() is the problem
    |                  ^^^^^^^^^ borrowed value does not live long enough
pool.execute(move || println!("{}", i));
    |             --------------------------------------- argument requires that `v2` is borrowed for `'static`

It is working fine without .iter(). Reason why I use it, it is for demonstration purposes in my code I use iter and zip to iter thru 2 vec of same size both of type String eg. urls.iter().zip(files_t4.iter()).

I do understand why I have error, but have no ideas how to solve it ?
I know that this is similar to How can I pass a reference to a stack variable to a thread?, but except trying another crate, not sure is it possible to use std::thread::scope like in first example.
I am learning hot to download files in Rust, and now what to see dow it is done with threadpool.
Any ideas are appreciated.

>Solution :

I do understand why I have error, but have no ideas how to solve it ?

Use .into_iter, or just iterate directly on the vector (does the same thing).

Because you’re using iter, the iterator is borrowing, so i is of type &String, and thus triggers a lifetime error as the compiler does not know that the scope will outlive the threadpool.

not sure is it possible to use std::thread::scope like in first example.

It is, however you’ll have to implement the "threadpool" by hand, as the threadpool crate does not support scoped threads / tasks. Alternatively, use Rayon which, aside from parallel iterators, provides explicit threadpool and scoped tasks. It also provides other interesting parallelism tools e.g. broadcast, join, and of course spawn.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading