Tokio task::spawn example

Published 411d ago

 ayebear

100% CPU utilization with default tokio runtime settings, just async code

use tokio::task;

#[tokio::main]
async fn main() {
    // If we don't collect, then the task::spawn's never get called until each iter of the for loop,
    // and it becomes fully sequential.
    let handles: Vec<_> = (0..100).map(|i| task::spawn(my_bg_task(i))).collect();
    println!("Spawned all tasks");
    for handle in handles {
        let result = handle.await.expect("my_bg_task failed");
        println!("Result: {result}");
    }
}

async fn my_bg_task(i: i64) -> i64 {
    println!("Task {i} start");
    let end = 10000000000 + i;
    let mut x = 0;
    for j in 0..end {
        if j % 2 == 0 {
            x += j;
        } else {
            x -= j;
        }
    }
    println!("Task {i} done");
    x
}

1

Please login or sign up to comment and collaborate