【发布时间】: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();
}
我尝试在特定的 self. 字段/方法上使用 Arc + Mutex,但这没有帮助。
您能否解释一下,如何在线程内使用self 引用来访问结构的字段/方法?
【问题讨论】:
-
请始终从
cargo check发布完整错误。
标签: rust rust-thread