如何将std :: sync :: RwLock引用传递给多个线程?

时间:2018-05-03 15:35:38

标签: multithreading rust borrowing

我希望以线程安全的方式让多个线程访问同一个数据结构。

我可以说到这一点,它说我的RwLock活得不够长!我理解Rust的贷款和借款,但我无法解决这个问题。

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]
}

编译器说

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...

我似乎无法找到任何这样做的例子。非常感谢任何想法或指示。

0 个答案:

没有答案