线程生命周期错误

时间:2015-01-26 16:40:45

标签: concurrency rust lifetime

我正试图实施游戏" Tower of Hanoi"在Rust中使用并发。老实说,我最后一次试图理解Rust的整个生命中的事情,但我还没有完成。这就是为什么我会得到一些我不理解的奇怪的终身错误。首先,这是重要的代码

fn move_plate<'a>(stack_a: &'a mut Vec<i32>, stack_b: &'a mut Vec<i32>, 
    stack_c: &'a mut Vec<i32>, moves: &'a mut Vec<(i32, i32)>) 
{
        let mut moves1: Vec<(i32, i32)> = Vec::new();
        let guard1 = Thread::scoped(
            move || { move_plate(stack_a, stack_c, stack_b, (1, 3, 2), &mut moves1); 
        });
        guard1.join().ok();
}

这是错误

error: cannot infer an appropriate lifetime due to conflicting requirements
    let guard1 = Thread::scoped(move || {
                     move_plate(height - 1, stack_a, stack_c, stack_b, (1, 3, 2), threads, depth + 1, &mut moves1);
                 });
note: first, the lifetime cannot outlive the expression at 93:25...
             let guard1 = Thread::scoped(move || {

note: ...so that the declared lifetime parameter bounds are satisfied
             let guard1 = Thread::scoped(move || {

note: but, the lifetime must be valid for the expression at 93:45...
             let guard1 = Thread::scoped(move || {
                 move_plate(height - 1, stack_a, stack_c, stack_b, (1, 3, 2), threads, depth + 1, &mut moves1);
             });
note: ...so type `closure[]` of expression is valid during the expression
             let guard1 = Thread::scoped(move || {
                 move_plate(height - 1, stack_a, stack_c, stack_b, (1, 3, 2), threads, depth + 1, &mut moves1);
             });
error: declared lifetime bound not satisfied
             let guard1 = Thread::scoped(move || {

我明白我必须避免线程超过函数,否则对移动的引用将会消失。但是,既然我加入了这个主题,那应该是好的,不应该吗?那时我错过了什么? 如果有人可以帮助我真的很好,我只是习惯那种很酷(但很复杂)的东西

1 个答案:

答案 0 :(得分:6)

这是Rust类型系统的已知限制。目前Rust允许仅在此数据满足Send绑定且Send暗示'static时才在线程之间发送数据 - 也就是说,可跨越线程边界发送的唯一引用是{{1 }}。

an RFC部分解除了此限制,允许跨任务发送非'static引用。我认为它已被接受,但它不是(这很奇怪)。已经创建了支持此类事物的API(这可能是您感到困惑的原因),但语言尚未调整。