首页 > 解决方案 > 使用具有生命周期的方法生成线程时出错

问题描述

我是并发的新手。上下文是我生成了一个线程,该线程在结构方法中使用具有生命周期的方法。然后我得到一个错误,由于需求冲突,无法推断出适当的生命周期

这是我的代码的简化示例。

use std::thread;
use std::time::Duration;

struct Printer{
    prefix: &'static str,
}

impl Printer {
    pub fn print(&self, text: String) {
        println!("{}: {}", self.prefix, text);
    }
    
    pub fn new(prefix: &'static str) -> Self {
        Printer {
            prefix: prefix
        }
    }
}

struct Foo<'a> {
    printer: &'a Printer
}

impl<'a> Foo<'a> {
    fn pop(&self) {
        thread::spawn(|| {
            self.printer.print(String::from("pop"));
        });
    }
    
    pub fn new(printer: &'a Printer) -> Self {
        Foo {
            printer: printer
        }
    }
}

fn main() {
    let printer = Printer::new("freaking");
    printer.print(String::from("hell"));
    let foo = Foo::new(&printer);
    
    foo.pop();
}
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
  --> src/main.rs:28:23
   |
28 |           thread::spawn(|| {
   |  _______________________^
29 | |             self.printer.print(String::from("pop"));
30 | |         });
   | |_________^
   |
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 26:6...
  --> src/main.rs:26:6
   |
26 | impl<'a> Foo<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/main.rs:28:23
   |
28 |           thread::spawn(|| {
   |  _______________________^
29 | |             self.printer.print(String::from("pop"));
30 | |         });
   | |_________^
   = note: expected `&&Foo<'_>`
              found `&&Foo<'a>`
   = note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src/main.rs:28:23: 30:10 self:&&Foo<'_>]` will meet its required lifetime bounds
  --> src/main.rs:28:9
   |
28 |         thread::spawn(|| {
   |         ^^^^^^^^^^^^^

error: aborting due to previous error

我怎样才能避免这个错误?它是并发的反模式吗?

标签: multithreadingconcurrencyrustthread-safetylifetime

解决方案


推荐阅读