【问题标题】:"`self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement" when access self. fields of struct from thread"`self` 有一个匿名的生命周期 `'_`,但是在访问 self 时它需要满足一个 `'static` 生命周期的要求"。来自线程的结构字段
【发布时间】:2022-06-13 18:33:28
【问题描述】:

我实现了结构,它在其中使用了一些线程。当我尝试使用 self.在线程内部,我收到一个错误:

self 具有匿名生命周期 '_,但它需要满足 'static 生命周期要求

这是我的代码:

use std::thread;
use std::sync::mpsc;
use std::time::Duration;
use rand::Rng;

struct Test {
    data: Vec<u8>,
    sender: mpsc::Sender<u8>, 
    receiver: mpsc::Receiver<u8>,
}

impl Test {
    pub fn new(
        sender: mpsc::Sender<u8>, 
        receiver: mpsc::Receiver<u8>
    ) -> Self {
        Self {
            data: vec![],
            sender,
            receiver,
        }
    }
    pub fn push(&mut self, item: u8) {
        self.data.push(item);
    }

    fn spawn_read_thread(&mut self) -> thread::JoinHandle<()> {
        thread::spawn(move || {
            let val = rand::thread_rng().gen();
            self.sender.send(val).unwrap();
            thread::sleep(Duration::from_millis(10));
        })
    }

    fn spawn_write_thread(&mut self) -> thread::JoinHandle<()> {
        thread::spawn(move || {
            let val = self.receiver.recv().unwrap();
            self.push(val);
            thread::sleep(Duration::from_millis(10));
        })
    }

    pub fn output(&mut self) {
        self.spawn_read_thread();
        self.spawn_write_thread();
    
        for _ in 0..20 {
            println!("{:?}", self.data);
            thread::sleep(Duration::from_millis(100));
        }
    }
}

fn main () {
    let (sender, receiver) = mpsc::channel();
    let test = Test::new(sender.clone(), receiver);
    test.output();
}

这是sandbox implementation

我尝试在特定的 self. 字段/方法上使用 Arc + Mutex,但这没有帮助。

您能否解释一下,如何在线程内使用self 引用来访问结构的字段/方法?

【问题讨论】:

  • 请始终从cargo check 发布完整错误。

标签: rust rust-thread


猜你喜欢
  • 1970-01-01
  • 2017-09-28
  • 2015-04-22
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多