在创建可在线程之间传递的二进制引用树时,“活动时间不够长”

时间:2014-10-04 06:07:45

标签: scope rust lifetime

我正在尝试编写一个可以在线程之间传递的二叉树,而不必每次都复制。我很难理解如何使用Rust限制生命周期。

use std::thread::spawn;

#[derive(Debug)]
struct Node<'a> {
    left: &'a i32,
    right: &'a i32,
}

fn main() {
    let l = 3;
    let r = 4;
    let n = Node {
        left: &l,
        right: &r,
    };

    spawn(|| {
        println!("{:?}", n);
    });
}
error[E0597]: `l` does not live long enough
  --> src/main.rs:13:15
   |
13 |           left: &l,
   |                 ^^ borrowed value does not live long enough
...
17 | /     spawn(|| {
18 | |         println!("{:?}", n);
19 | |     });
   | |______- argument requires that `l` is borrowed for `'static`
20 |   }
   |   - `l` dropped here while still borrowed

error[E0597]: `r` does not live long enough
  --> src/main.rs:14:16
   |
14 |           right: &r,
   |                  ^^ borrowed value does not live long enough
...
17 | /     spawn(|| {
18 | |         println!("{:?}", n);
19 | |     });
   | |______- argument requires that `r` is borrowed for `'static`
20 |   }
   |   - `r` dropped here while still borrowed

error[E0373]: closure may outlive the current function, but it borrows `n`, which is owned by the current function
  --> src/main.rs:17:11
   |
17 |     spawn(|| {
   |           ^^ may outlive borrowed value `n`
18 |         println!("{:?}", n);
   |                          - `n` is borrowed here
   |
note: function requires argument type to outlive `'static`
  --> src/main.rs:17:5
   |
17 | /     spawn(|| {
18 | |         println!("{:?}", n);
19 | |     });
   | |______^
help: to force the closure to take ownership of `n` (and any other referenced variables), use the `move` keyword
   |
17 |     spawn(move || {
   |           ^^^^^^^

我理解为什么它会认为他们的生活时间不够长,但我应该如何重组这些呢?

1 个答案:

答案 0 :(得分:3)

在您的情况下,您创建一个Node对象,其中引用了您在main()函数中定义的变量,并将其传递给新线程。问题是你绝对不能保证这个线程会在main()的线程之前完成,并且你冒着原始变量在引用之前超出范围的风险,因此错误。

鉴于您希望构建一个树,我认为最简单的解决方法是让您的Node类型拥有其字段,如下所示:

#[derive(Debug)]
struct Node {
    left: i32,
    right: i32,
}

您将不再有生命问题。

要在多个线程之间共享它而不复制它,您可以使用std::sync::Arc包装器;它正是出于这个目的。你可以这样做:

use std::sync::Arc;

fn main() {
    let n = Arc::new(Node { left: 3, right: 4 });

    for _ in 0..10 {
        let n_thread = n.clone();
        spawn(move || {
            println!("{:?}", n_thread);
        });
    }
}

如果您还需要让其他线程写入Node的访问权限,您可能希望将其包含在MutexRwLock中,将整个内容保留在Arc