2

在我的一个 actix-web 处理程序中,我想调用一个在后台运行并立即向用户返回响应的函数:

async fn heavy_computation() -> {
    // do some long running computation
}

async fn index(req: HttpRequest) -> impl Responder {
    // start computation
    heavy_computation(); 
    
    // render and return template
    let out context = Context::new();
    context.insert("foo", "bar");
    render_template("my_template.html", &context)

    // computation finishes
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(web::resource("/").route(web::get().to(index)))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

如果我await将来在计算之后才完成响应,如果我不这样做await,则根本不会执行该函数。

4

1 回答 1

1

假设您将tokio其用作异步运行时,您可以使用以下命令生成两个任务,tokio::task::spawn然后将它们加入tokio::join

use tokio::task;
use tokio::time;
use std::time::Duration;

async fn heavy_computation() {
    time::delay_for(Duration::from_millis(2000)).await;
    println!("heavy computation finished");
}

async fn light_computation() {
    time::delay_for(Duration::from_millis(500)).await;
    println!("light computation finished");
}

#[tokio::main]
async fn main() {
    let heavy = task::spawn(heavy_computation());
    println!("computation started");
    let light = task::spawn(async move {
        for _ in 0..3 {
            light_computation().await;
        }
    });
    let (a, b) = tokio::join!(heavy, light);
    // use the results so the compiler doesn't complain
    a.unwrap();
    b.unwrap();
}

链接到游乐场

于 2020-07-19T17:33:37.667 回答