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



我有一个应用程序,主要作为一个web服务器,我正试图实现一个后台任务,每秒从主线程变异变量。

下面的代码片段与我的实际代码结构相似,这段代码位于main函数内部:

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;
...

你需要在async上下文中移动它:

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;
}
});

游乐场