本文介绍了再探:如何将不可变的参数传递给线程?(关于终生)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题得到解答.

但是当我稍微修改一下代码后,它又不会再次工作,并且出现类似于上一个问题中的错误的编译错误.我现在怎么了?

But when I modified the code a little, it does not work again with a compilation error similar to the error in the previous question. What is my error now?

use std::thread;

#[derive(Clone)]
struct Params<'a> {
    x: &'a i32,
}

struct State<'a> {
    params: &'a Params<'a>,
    y: i32,
}

impl<'a> State<'a> {
    fn new(params: &'a Params<'a>) -> Self {
        State {
            params,
            y: 0,
        }
    }
    fn start(&mut self) -> thread::JoinHandle<()> {
        let params = self.params.clone();
        thread::spawn(move || { params; /* ... */ })
    }
}
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/lib.rs:21:34
   |
21 |         let params = self.params.clone();
   |                                  ^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 13:6...
  --> src/lib.rs:13:6
   |
13 | impl<'a> State<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/lib.rs:21:34
   |
21 |         let params = self.params.clone();
   |                                  ^^^^^
   = note: expected `&Params<'_>`
              found `&Params<'a>`
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/lib.rs:22:23: 22:52 params:Params<'_>]` will meet its required lifetime bounds
  --> src/lib.rs:22:9
   |
22 |         thread::spawn(move || { params; /* ... */ })
   |         ^^^^^^^^^^^^^

推荐答案

我建议您使用引用计数类型(Arc)而不是使用引用计数类型(Arc),这样您就不必担心生存期了.

Instead of using references I would suggest using a reference counted type (Arc), that way you do not need to worry about lifetimes.

use std::thread;
use std::sync::Arc;

#[derive(Clone)]
struct Params {
    x: i32,
}

struct State {
    params: Arc<Params>,
    y: i32,
}

impl State {
    fn new(params: &Arc<Params>) -> Self {
        State {
            params: params.clone(),
            y: 0,
        }
    }
    fn start(&self) -> thread::JoinHandle<()> {
        let params = self.params.clone();
        thread::spawn(move || { params; /* ... */ })
    }
}

如果以后想要更改状态,则需要使用 Arc< Mutex<参数>> .

If you want to mutate the state later on, you would need to wrap the Params type in the State struct with a Mutex like Arc<Mutex<Params>>.

有关该主题的更多信息:

More on the topic:

这篇关于再探:如何将不可变的参数传递给线程?(关于终生)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 08:22