multithreading - 使用具有生命周期的方法生成线程时出错
问题描述
我是并发的新手。上下文是我生成了一个线程,该线程在结构方法中使用具有生命周期的方法。然后我得到一个错误,由于需求冲突,无法推断出适当的生命周期
这是我的代码的简化示例。
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
我怎样才能避免这个错误?它是并发的反模式吗?
解决方案
推荐阅读
- flutter - Flutter web nav 2.0:防止注销用户直接访问URL
- python - python中的if-for-else嵌套集合理解
- javascript - 引导侧边栏导航菜单滚动到活动面板标题的顶部
- sql - 我们可以在选择查询中使用什么而不是游标
- reactjs - Antd 无法将数据输入动态输入字段
- python - 基于动态事件的 Python 算法构建 n 个 OHLC 柱
- c - 是否有任何有效的方法(库或函数或算法)以压缩稀疏行格式删除或附加特定的行和列组件?
- jsf - f:validateRegex 在将 jsf2.1 项目部署到 weblogic12c 时始终检查
- jenkins-pipeline - 如果上传失败,Nexus Artifact Upload Plugin 不会失败管道
- scala - 无法从 spark scala 中的列名中删除空格