我有两部分代码要循环运行。有时我需要让循环“休眠”,让每次迭代都跳过第二部分。循环应在设定的时间后停止休眠(例如使用调用 thread::sleep
的线程)。我该如何实现?
use std::thread;
let mut sleeping = false;
let mut handle = thread::spawn(|| {});
loop {
part_1();
if sleeping {
continue;
}
part_2();
if some_condition {
sleeping = true;
handle = thread::spawn(|| thread::sleep_ms(100));
}
}
在这个例子中,如果满足条件,part_2
调用将被跳过一些迭代。我的用例是继续在游戏中运行图形更新,同时卡住游戏的逻辑(例如倒数计时器)。
最佳答案
不需要线程的开销,甚至不需要 sleep 。只需跟踪您应该延迟执行代码的时间,直到:
use std::time::{Duration, Instant};
fn part_1() {}
fn part_2() {}
fn some_condition() -> bool {
false
}
fn main() {
let mut sleep_until = None;
loop {
part_1();
if let Some(until) = sleep_until {
if until > Instant::now() {
continue;
}
}
part_2();
if some_condition() {
let now = Instant::now();
let until = now + Duration::from_millis(500);
sleep_until = Some(until);
}
}
}
尽管我可能会避免使用 continue
在这里,而是将逻辑嵌入到:
use std::time::{Duration, Instant};
fn perform_physics_calculation() {}
fn perform_graphics_render() {}
fn main() {
let mut next_graphics_update = Instant::now();
let graphics_delay = Duration::from_millis(500);
loop {
let now = Instant::now();
perform_physics_calculation();
if next_graphics_update <= now {
perform_graphics_render();
next_graphics_update = now + graphics_delay;
}
}
}
请注意,在一个案例中我使用了 Option<Instant>
在另一个中,我只使用 Instant
;这两种情况都有意义。
关于multithreading - 线程休眠时跳过部分循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198393/