Rust:在子线程内部异步改变父状态

Rust: mutating parent state asynchronously inside of child thread

我有一个主要用作 Web 服务器的应用程序,我正在尝试执行一个后台任务,该任务每秒从主线程更改变量。

以下代码片段与我的实际代码结构相似,这段代码在主函数中:

let mut counter: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));

thread::spawn(move || async {
    let mut interval = time::interval(time::Duration::from_secs(1));
    let mut counter_clone = counter.lock().await;
    loop {
        interval.tick().await;
        *counter_clone += 1;
    }
});

编译器有以下消息确实有道理,但我正在尝试做的似乎是一个常见问题,我希望有人可以提供一些指导。

编译器错误:

async block may outlive the current function, but it borrows `counter`, which is owned by the current function

may outlive borrowed value `counter`

我的想法是,主线程死了,子线程也死了。

我们将不胜感激。

编译器帮你:

help: to force the async block to take ownership of `counter` (and any other referenced variables), use the `move` keyword
   |
10 |     thread::spawn(move || async move {
11 |         let mut interval = time::interval(time::Duration::from_secs(1));
12 |         let mut counter_clone = counter.lock().await;
13 |         loop {
14 |             interval.tick().await;
15 |             *counter_clone += 1;
 ...

您需要在异步上下文中移动它:

    thread::spawn(|| async move {
        let mut interval = time::interval(time::Duration::from_secs(1));
        let mut counter_clone = counter.lock().await;
        loop {
            interval.tick().await;
            *counter_clone += 1;
        }
    });

Playground