gpt4 book ai didi

file - 如何从文件更改中热加载结构

转载 作者:行者123 更新时间:2023-12-03 11:36:32 25 4
gpt4 key购买 nike

我正在尝试在文件更改时进行热重装,但出现此错误:
预期实现Fn特性的闭包,但此闭包仅实现FnMut此闭包实现FnMut,而不是Fn我对从此库传递给new_immediate函数的闭包似乎不满意:

notify = { version = "5.0.0-pre.4", features = ["serde"] }
我的代码:
use announcer::messages::{load_config, save_config, Config, Message};
use notify::{
event::ModifyKind, Error, Event, EventFn, EventKind, RecommendedWatcher, RecursiveMode, Watcher,
};
use tide::{http, Body, Response};

const CONFIG_PATH: &str = "config.json";

#[async_std::main]
async fn main() -> tide::Result<()> {
let mut config = load_config(CONFIG_PATH).unwrap();

let mut watcher: RecommendedWatcher =
Watcher::new_immediate(|result: Result<Event, Error>| {
let event = result.unwrap();

if event.kind == EventKind::Modify(ModifyKind::Any) {
config = load_config(CONFIG_PATH).unwrap();
}
})?;

watcher.watch(CONFIG_PATH, RecursiveMode::Recursive)?;

let mut app = tide::with_state(config);
app.listen("127.0.0.1:8080").await?;

Ok(())
}
我在Rust Discord初学者聊天中问,17cupsofcoffee说我应该使用互斥体,但是我不知道该怎么做。

最佳答案

这里的问题是,您正在另一个线程中生成此监视功能,并且可能在一个线程中写入它,而在另一个线程中读取它,从而导致竞争状态。您应该使用 Mutex ,并对其进行lock来获得防护,该防护可以让您对其进行读取/写入。由于tide的全局状态也需要Clone,因此您还应该将其包装在 Arc 中,后者是一个线程安全的引用计数指针:

use announcer::messages::{load_config, save_config, Config, Message};
use notify::{
event::ModifyKind, Error, Event, EventFn, EventKind, RecommendedWatcher, RecursiveMode, Watcher,
};
use tide::{http, Body, Response};
// necessary imports
use std::sync::{Arc, Mutex};

const CONFIG_PATH: &str = "config.json";

#[async_std::main]
async fn main() -> tide::Result<()> {
// we store it in an Arc<Mutex<T>>
let config = Arc::new(Mutex::new(load_config(CONFIG_PATH).unwrap()));
let cloned_config = Arc::clone(&config);

let mut watcher: RecommendedWatcher =
Watcher::new_immediate(move |result: Result<Event, Error>| {
let event = result.unwrap();

if event.kind == EventKind::Modify(ModifyKind::Any) {
// we lock the mutex to acquire a mutable guard and write to that
match load_config(CONFIG_PATH) {
Ok(new_config) => *cloned_config.lock().unwrap() = new_config,
Err(error) => println!("Error reloading config: {:?}", error),
}
})?;

watcher.watch(CONFIG_PATH, RecursiveMode::Recursive)?;

let mut app = tide::with_state(config);
app.listen("127.0.0.1:8080").await?;

Ok(())
}
然后,每当需要从状态读取时,只需锁定互斥锁即可:
let config_guard = req.state().lock().unwrap();
println!("{:?}", config_guard.foo);
有关其他引用:
  • The Rust Language: Shared-State Concurrency
  • 关于file - 如何从文件更改中热加载结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65457485/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com