1

I am a Rust beginner and I do not fully understand lifetimes. I wrote this code which throws an error:

use std::{
    thread,
    time
};

const BLOCKS_PER_DAY: u32 = 7200;

fn main() -> Result<(), std::io::Error> {

    let end_block_number = 1_000_000;

    let block_queries: Vec<u32> = ((end_block_number.as_u32() - BLOCKS_PER_DAY)..=end_block_number.as_u32()).collect();
    let providers: Vec<u64> = vec![
        1,
        2,
        3,
        4,
        5,
        6
    ];
    let mut providers_iter = providers.iter();

    let query_amount_per_provider = block_queries.len() / providers.len();
    let mut block_slices = block_queries.chunks(query_amount_per_provider);
    
    let mut provider_handles = vec![];
    while let (Some(blocks_to_query), Some(&provider)) = (block_slices.next(), providers_iter.next()) {
        let handle = thread::spawn(move || {
            for i in blocks_to_query {
                // query block_number
                println!("Provider {} querying block {}", provider, i);
                let delay = time::Duration::from_millis(500 * provider);
                thread::sleep(delay);
            }
        });
        provider_handles.push(handle);
    }


    for handle in provider_handles {
        handle.join().unwrap();
    }

    Ok(())
}

The error is "block_queries does not live long enough. Borrowed value does not live long enough".

  1. I am not sure where the value is dropped.
  2. I do not understand how I can bypass the error and make the code work.
Cizia
  • 428
  • 5
  • 11
  • 1
    If you are a Rust beginner I would not recommend starting with a multi-threaded application. Have you read [the book](https://doc.rust-lang.org/book/title-page.html) yet? If you do wanna soldier on with this, have a look at [`thread::scope`](https://doc.rust-lang.org/stable/std/thread/fn.scope.html). – isaactfa Jun 17 '23 at 15:40
  • Yes I did read it all but I'll check it again. I have been coding a lot in rust recently but I'm still wrapping my head around some concepts. I need this code to execute simultaneously – Cizia Jun 17 '23 at 15:44
  • I see. The "trouble" with Rust's threading model is that by default, they cannot borrow anything because they could outlive the thread that spawned them and thus the data they borrowed. – isaactfa Jun 17 '23 at 15:51
  • 1. The value is dropped at the end of `main`, which is *possibly before* the end of each spawned thread's function. You have ensured that doesn't happen by joining them, but this is outside the compiler's ability to verify. – drewtato Jun 17 '23 at 16:14
  • 2. You can use scoped threads or rayon, which that other answer explains. Rayon makes this quite easy since you are already operating on an iterator. You probably don't even need `chunks`. – drewtato Jun 17 '23 at 16:17

0 Answers0