0

I want to have give multiple threads access to the same data structure in a thread-safe manner.

I can get as far as this, where it says that my RwLock does not live long enough! I understand the lending and borrowing of Rust, but this I can't wrap my head around.

use std::sync::RwLock;
use std::thread;

fn func<'a>(vec_lock: &'a RwLock<Vec<i32>>) {
    let mut vec = vec_lock.write().unwrap();
    vec.push(2);
}

fn main() {
    let v: Vec<i32> = Vec::new(); // Shared data
    let v_lock = &RwLock::new(v); // RwLock ref

    let t1 = thread::spawn(move || func(v_lock)); // Give lock ref to func
    let t2 = thread::spawn(move || func(v_lock)); // Give lock ref to func
    t1.join().unwrap(); // Wait
    t2.join().unwrap();

    // Here v should be [2,2]
}

The compiler says

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:11:19
   |
11 |     let v_lock = &RwLock::new(v);
   |                   ^^^^^^^^^^^^^^ temporary value does not live long enough
...
19 | }
   | - temporary value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

I cannot seem to find any examples that do this. Any ideas or pointers are greatly appreciated.

RAM
  • 2,257
  • 2
  • 19
  • 41
Anders
  • 75
  • 9
  • I believe this has already been answered by [How can I pass a reference to a stack variable to a thread?](https://stackoverflow.com/q/32750829/155423). Further information can be found in [Lifetime troubles sharing references between threads](https://stackoverflow.com/q/28654978/155423). Please [edit] your question to explain how this is different from these existing questions. Otherwise, we can mark this as already answered. – Shepmaster May 03 '18 at 15:43
  • [The duplicate applied to your question](https://play.rust-lang.org/?gist=36740c478e6de6722f4d61c25a0c488e&version=stable&mode=debug). – Shepmaster May 03 '18 at 15:56
  • Thanks for your help :) Greatly appreciated – Anders May 04 '18 at 11:02

0 Answers0