作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
struct ThreadHolder{
state: ???
thread: ???
}
impl ThreadHolder {
fn launch(&mut self) {
self.thread = ???
// in thread change self.state
}
}
#[test]
fn test() {
let mut th = ThreadHolder{...};
th.launch();
// thread will be destroy as soon as th go out of scope
}
我觉得lifetime有东西可以处理,但是不知道怎么写。
最佳答案
您想要的是如此简单,以至于您甚至不需要它以任何方式可变,然后跨线程共享它变得微不足道,除非您想重置它。你说你需要离开一个线程,出于某种原因,因此我假设你不关心这个。
您可以改为在每个滴答声中对其进行轮询(大多数游戏都以滴答声运行,所以我认为实现它不会有任何问题)。
我将提供使用 sleep 的示例,所以这不是最准确的事情,它在最后一个亚秒持续时间内非常明显,但无论如何我都不想为您完成工作,互联网上有足够的资源可以帮助您处理它。
这里是:
use std::{
sync::Arc,
thread::{self, Result},
time::{Duration, Instant},
};
struct Timer {
end: Instant,
}
impl Timer {
fn new(duration: Duration) -> Self {
// this code is valid for now, but might break in the future
// future so distant, that you really don't need to care unless
// you let your players draw for eternity
let end = Instant::now().checked_add(duration).unwrap();
Timer { end }
}
fn left(&self) -> Duration {
self.end.saturating_duration_since(Instant::now())
}
// more usable than above with fractional value being accounted for
fn secs_left(&self) -> u64 {
let span = self.left();
span.as_secs() + if span.subsec_millis() > 0 { 1 } else { 0 }
}
}
fn main() -> Result<()> {
let timer = Timer::new(Duration::from_secs(10));
let timer_main = Arc::new(timer);
let timer = timer_main.clone();
let t = thread::spawn(move || loop {
let seconds_left = timer.secs_left();
println!("[Worker] Seconds left: {}", seconds_left);
if seconds_left == 0 {
break;
}
thread::sleep(Duration::from_secs(1));
});
loop {
let seconds_left = timer_main.secs_left();
println!("[Main] Seconds left: {}", seconds_left);
if seconds_left == 5 {
println!("[Main] 5 seconds left, waiting for worker thread to finish work.");
break;
}
thread::sleep(Duration::from_secs(1));
}
t.join()?;
println!("[Main] worker thread finished work, shutting down!");
Ok(())
}
顺便说一句,这种实现在任何其他语言中都没有任何不同,所以请不要为此责怪 Rust。它不是最简单的语言,但它提供了足够多的工具,只要您付出努力,就可以从头开始构建您想要的任何东西。
祝你好运:)
关于rust - 如何让结构持有一个线程并在它超出范围时立即销毁线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58971219/
我是一名优秀的程序员,十分优秀!