Problem with references shared among threads and lifetimes

⚓ Rust    📅 2025-09-16    👤 surdeus    👁️ 1      

surdeus

I have a vec in my main function. It is referenced by a struct with a lifetime. Both the struct and the vec are used in threads spawned by my main function:

use std::thread;
use std::sync::{Arc,Mutex};

#[derive(Debug)]
struct Struct<'a> {
    v: &'a Vec<i32>,
}

fn bla(v: &Vec<i32>) {
    println!("{:?}", *v);
}

fn blubb(s: &Struct) {
    println!("{:?}", s);
}

fn main() {
    let v = vec![1,2,3];
    let shared_struct = Arc::new(Mutex::new(Struct{v : &v}));
    let v = Arc::new(v.clone());
    let mut handles = Vec::new();
    for _ in 0..2 {
        let v = Arc::clone(&v);
        let handle = thread::spawn(move || {
            loop {
                bla(&v);
                blubb(&shared_struct.lock().unwrap());
                break;
            }
        });
        handles.push(handle);
    }
    for handle in handles {
        handle.join().unwrap();
    }
    println!("done!");
}

(Playground)

I get the following errors. How can I fix them without unnecessary clone()'s? Thanks!

   Compiling playground v0.0.1 (/playground)
error[E0597]: `v` does not live long enough
  --> src/main.rs:19:56
   |
18 |       let v = vec![1,2,3];
   |           - binding `v` declared here
19 |       let shared_struct = Arc::new(Mutex::new(Struct{v : &v}));
   |                                                          ^^ borrowed value does not live long enough
...
24 |           let handle = thread::spawn(move || {
   |  ______________________-
25 | |             loop {
26 | |                 bla(&v);
27 | |                 blubb(&shared_struct.lock().unwrap());
...  |
30 | |         });
   | |__________- argument requires that `v` is borrowed for `'static`
...
37 |   }
   |   - `v` dropped here while still borrowed

error[E0382]: use of moved value: `shared_struct`
  --> src/main.rs:24:36
   |
19 |     let shared_struct = Arc::new(Mutex::new(Struct{v : &v}));
   |         ------------- move occurs because `shared_struct` has type `Arc<Mutex<Struct<'_>>>`, which does not implement the `Copy` trait
...
22 |     for _ in 0..2 {
   |     ------------- inside of this loop
23 |         let v = Arc::clone(&v);
24 |         let handle = thread::spawn(move || {
   |                                    ^^^^^^^ value moved into closure here, in previous iteration of loop
25 |             loop {
   |             ---- inside of this loop
26 |                 bla(&v);
27 |                 blubb(&shared_struct.lock().unwrap());
   |                        ------------- use occurs due to use in closure
   |
help: consider moving the expression out of the loop so it is only moved once
   |
22 ~     let mut value = shared_struct.lock();
23 ~     for _ in 0..2 {
24 |         let v = Arc::clone(&v);
...
27 |                 bla(&v);
28 ~                 blubb(&value.unwrap());
   |

Some errors have detailed explanations: E0382, E0597.
For more information about an error, try `rustc --explain E0382`.
error: could not compile `playground` (bin "playground") due to 2 previous errors

2 posts - 2 participants

Read full topic

🏷️ Rust_feed