如何将不可变参数传递给线程?(关于终生) [英] How to pass immutable parameters to a thread? (about lifetimes)

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

问题描述

让线程状态由不可变参数 Params 和其余(可变)状态 State 组成.

Let thread state consists of immutable parameters Params and the rest of the (mutable) state State.

我正在尝试模拟生成一个由参数 Params :

I am trying to mock spawning a thread that does something being controlled by parameters Params:

use std::thread;

struct Params {
    x: i32,
}

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

impl<'a> State<'a> {
    fn new(params: &Params) -> State {
        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
  --> test.rs:20:34
   |
20 |         let params = self.params.clone();
   |                                  ^^^^^
   |
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 12:6...
  --> test.rs:12:6
   |
12 | impl<'a> State<'a> {
   |      ^^
note: ...so that the types are compatible
  --> test.rs:20:34
   |
20 |         let params = self.params.clone();
   |                                  ^^^^^
   = note: expected  `&&Params`
              found  `&&'a Params`
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@test.rs:21:23: 21:42 params:&Params]` will meet its required lifetime bounds
  --> test.rs:21:9
   |
21 |         thread::spawn(move || { params; /* ... */ })
   |         ^^^^^^^^^^^^^

我理解为什么它不起作用:该线程可以无限期地运行,并且 params 可以在终止之前被销毁.显然这是一个错误.

I understand why it does not work: The thread could run indefinitely long, and the params could be destroyed before it is terminated. That's clearly an error.

现在说明什么是使 params 至少与线程一样长的正确方法.换句话说,有助于更正上面的代码.一生该怎么办?

Now explain what is the proper way to make params long at least as long as the thread. In other words, help to correct the above code. What should I do with lifetimes?

推荐答案

使用 clone move lambda,您获得了正确的主意,但您忘记了一个细节: Params 不是 Clone !因此,编译器在看到 self.params.clone()并克隆了该引用之后,会尽力而为.

You got the right idea with using clone and a move lambda, but you forgot one detail: Params isn't Clone! Therefore the compiler did the best it could when it saw self.params.clone() and cloned… the reference.

这就是错误消息在此处具有两个& 的原因:

That's why the error messages have two & here:

   = note: expected  `&&Params`
              found  `&&'a Params`

使用#[derive(Clone)] struct Params {/*…*/} .

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆