How to sum the value returned from concurrent tasks?

I'm trying to spawn 10 tasks and run them concurrently, and afterward sum the value returned by each task.

async fn slow_running_task() -> anyhow::Result<u32> {
    println!("slow_running_task");
    tokio::time::sleep(time::Duration::from_secs(5)).await;
    println!("slow_running_task done");
    return Ok(5);
}

async fn test_tokio_spawn_multiple() {
    let mut tasks = vec![];

    for _ in 0..10 {
        println!("push");
        tasks.push(slow_running_task());
    }
    let total_took_sec = Arc::new(AtomicUsize::new(0));
    futures::stream::iter(tasks).for_each_concurrent(10, |result| async move {
        let _cloned = total_took_sec.clone();
        let res = result.await;
        match res {
            Ok(took_sec) => {
                _cloned.fetch_add(took_sec as usize, std::sync::atomic::Ordering::SeqCst);
                // println!("{}", took_sec);
            }
            Err(_) => println!("failed"),
        };
    });
    let cloned2 = total_took_sec.clone();
    println!("{}", cloned2.load(std::sync::atomic::Ordering::SeqCst));
}

but I'm getting the following error:

error: cannot move out of `total_took_sec`, a captured variable in an `FnMut` closure
label: `total_took_sec` is moved here
cannot move out of `total_took_sec`, a captured variable in an `FnMut` closure
`total_took_sec` is moved hererustcClick for full compiler diagnostic
main.rs(81, 9): captured outer variable
main.rs(82, 58): captured by this `FnMut` closure
main.rs(83, 23): variable moved due to use in generator
main.rs(83, 23): move occurs because `total_took_sec` has type `Arc<AtomicUsize>`, which does not implement the `Copy` trait

how is this typically done in rust? Thanks

-    futures::stream::iter(tasks).for_each_concurrent(10, |result| async move {
-        let _cloned = total_took_sec.clone();
+    futures::stream::iter(tasks).for_each_concurrent(10, |result| {
+        let _cloned = total_took_sec.clone();
+        async move {

total_took_sec is moved into the closure by async move, so not to do so, put it before the async block. Rust Playground

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.