【问题标题】:Moving non-Copy variable into async closure: captured variable cannot escape `FnMut` closure body将非复制变量移动到异步闭包中:捕获的变量无法逃脱 `FnMut` 闭包体
【发布时间】:2021-06-13 17:25:05
【问题描述】:

我正在尝试让clokwerk 安排一个异步函数每 X 秒运行一次。

The docs 显示这个例子:

// Create a new scheduler
let mut scheduler = AsyncScheduler::new();
// Add some tasks to it
scheduler
    .every(10.minutes())
        .plus(30.seconds())
    .run(|| async { println!("Simplest is just using an async block"); });
// Spawn a task to run it forever
tokio::spawn(async move {
  loop {
    scheduler.run_pending().await;
    tokio::time::sleep(Duration::from_millis(100)).await;
  }
});

我最初的尝试:

    let config2 = // define a Config struct, Config
    let pg_pool2 = // get a sqlx connection pool, Pool<Postgres>

    //I assume I need shared references so I use Arc
    let pg_pool2 = Arc::new(pg_pool2);
    let config2 = Arc::new(config2);

    let mut scheduler = AsyncScheduler::new();

    scheduler.every(5.seconds()).run(|| async {
        println!("working!");
        pull_from_main(pg_pool2.clone(), config2.clone()).await;
    });

    tokio::spawn(async move {
        loop {
            scheduler.run_pending().await;
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    });

编译器抱怨pg_pool2config2 可能比借用的值更长,并建议添加move。公平的。让我们试试吧。

我的第二次尝试:

    //rest the same
    scheduler.every(5.seconds()).run(move || async {
    //rest the same

这一次我得到了一个我自己无法破译的错误:

error: captured variable cannot escape `FnMut` closure body
  --> src/main.rs:80:46
   |
75 |       let pg_pool2 = Arc::new(pg_pool2);
   |           -------- variable defined here
...
80 |       scheduler.every(5.seconds()).run(move || async {
   |  ____________________________________________-_^
   | |                                            |
   | |                                            inferred to be a `FnMut` closure
81 | |         println!("working!");
82 | |         pull_from_main(pg_pool2.clone(), config2.clone()).await;
   | |                        -------- variable captured here
83 | |     });
   | |_____^ returns an `async` block that contains a reference to a captured variable, which then escapes the closure body
   |
   = note: `FnMut` closures only have access to their captured variables while they are executing...
   = note: ...therefore, they cannot allow references to captured variables to escape

有人可以帮我了解问题所在以及如何解决吗?

注意:我之前看到过这个问题,但我很难将答案应用到我的案例中。

  • here 涉及一个可变变量,我没有。
  • here 解决方案是将变量包含为 fn 参数,我不能这样做,因为闭包不需要参数。当我不这样做时,它似乎也从导致问题的闭包返回了一个值。

我也是初学者,所以也许他们确实申请了,但我没有看到联系:)

【问题讨论】:

  • HS:“我也是一个初学者” tokio 和 async 世界一般不建议 rust 初学者。

标签: rust closures


【解决方案1】:

为了了解发生了什么,我将重新格式化代码以使其更加清晰明确:

您的原始代码:

  scheduler
    .every(5.seconds())
    .run(move || async {
        do_something(arc.clone());
    });

相当于:

  scheduler
    .every(5.seconds())
    .run(move || {
       return async {
          do_something(arc.clone());
       }
    });

所以你创建了一个闭包,它的类型是FnMut(并且它返回一个实现Future的类型)。这意味着您的闭包可以被多次调用,并且每次调用都应该产生一个新的未来。但是return async{} 移动你的Arc 离开了闭包,这意味着它只能被调用一次。想象一下,你的钱包里有一张 10 美元的钞票。如果你把它拿出来花掉,那么你就不能把它拿出来第二次花掉,因为它根本就不存在了。

那么我们该如何解决呢?实际上这很容易——你必须先克隆你的Arc,然后再将它移动到async 块。因此,您将只移动克隆:

    let arc = Arc::new(whatever);   
    scheduler
        .every(5.seconds())
        .run(move || {
             // Clone the arc and move the clone!!! 
             // The original arc will remain in the closure, 
             // so it can be called multiple times.
            let x = arc.clone(); 
            async move { 
                do_something(x);
            }
        });

【讨论】:

  • 感谢这么简单的解释!另外,我终于明白了“异步移动 || ..”和“移动 || 异步 ..”之间的区别。谢谢老兄!
猜你喜欢
  • 2020-10-14
  • 2019-04-01
  • 2015-04-15
  • 2020-01-16
  • 2022-11-19
  • 2016-02-13
  • 2016-01-28
  • 1970-01-01
相关资源
最近更新 更多