multithreading - 线程休眠时跳过部分循环

标签 multithreading rust

我有两部分代码要循环运行。有时我需要让循环“休眠”,让每次迭代都跳过第二部分。循环应在设定的时间后停止休眠(例如使用调用 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/

相关文章:

java - 使用 ExecutorService 在具有通过循环传递的不同参数的类中同时执行方法时出现问题

c++ - 为什么一个子线程的执行时间比整个应用程序的执行时间多

multithreading - TThreadList和 “with”语句

java - 在 Java 中使用 Thread#stop() 来终止一个正在运行的线程是否可以接受?

error-handling - Rust Snafu缺少 'source'字段

Rust 按特定字节拆分字节向量

java - 从子线程获取http session ?

rust - 优化级别 `-Os` 和 `-Oz` 在 Rust 中有什么作用?

recursion - 递归结构错误生命周期(无法为函数调用中的生命周期参数推断适当的生命周期... [E0495])

rust - 使用 None 访问 Rust 中的嵌套 HashMap