multithreading - 为什么不能通过函数安排计时器?

标签 multithreading asynchronous rust timer

我正在使用一个名为timer的 crate ,并且尝试将计时器“guard”放入哈希图中以存储它,以便可以在结束之前将其删除或确保不创建重复项。
问题在于,当通过函数将其插入到哈希图中时,计时器不会触发,但是如果将函数的主体移至main,则计时器可以正常工作。

extern crate chrono;
extern crate timer;

use std::collections::HashMap;
use std::thread;
use std::time::Duration;

fn insert_to_guard_map(guard_map: &mut HashMap<i32, timer::Guard>) {
    let timer = timer::Timer::new();
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, guard);
}

fn main() {
    let mut guard_map = HashMap::new();

    insert_to_guard_map(&mut guard_map);
    thread::sleep(Duration::from_secs(4));
}

最佳答案

Timer Guard 的文档中提到,如果删除了TimerGuard,则最终取消了计划的执行。
因此,在那种情况下,请将timerguard都插入 HashMap

use timer::{Guard, Timer};

fn insert_to_guard_map(guard_map: &mut HashMap<i32, (Timer, Guard)>) {
    let timer = Timer::new();
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, (timer, guard));
}
或者(可能更好),将Timer的引用传递给insert_to_guard_map()
use timer::{Guard, Timer};

fn insert_to_guard_map(guard_map: &mut HashMap<i32, Guard>, timer: &Timer) {
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, guard);
}

fn main() {
    let timer = Timer::new();
    let mut guard_map = HashMap::new();

    insert_to_guard_map(&mut guard_map, &timer);
    thread::sleep(Duration::from_secs(4));
}

关于multithreading - 为什么不能通过函数安排计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65550087/

相关文章:

rust - 我如何拥有只接受 &self 的自定义记录器的内部状态?

function - 闭包:预期的 u32 找到类型参数

c++ - 什么是内存位置?

java - 尝试在 Java 中使用多线程对 Arraylist 的数字求和时出现 ConcurrentModificationException

java - 有没有办法更改启动线程的名称?

java - Spring批处理ApplicationContext

iphone - 加载和解析 xml 文档卡住了 Iphone 中的 GUI

node.js - 异步移动 Node 中的文件数组

rust - 手动删除引用包装器的Rust生命周期问题

python - 当我在 python 和 pyqt 中关闭应用程序时不运行类析构函数