How tokio spawn differ from the join macro?

Im trying to explore tokio and async, and i'm unable to understand the spawn function in tokio::spawn. Is it possible to write above code with spawn instead of join macro?

use simple_logger::SimpleLogger;
use std::thread::sleep as sync_sleep;
use tokio::time::{sleep, Duration, Instant};

#[tokio::main]
async fn main() {
    SimpleLogger::new().init().unwrap();

    let start = Instant::now();

    // asynchronous call
    tokio::join!(async_read_one(), async_read_two());

    let end = Instant::now();
    log::info!("Running Time: {:#?}", end - start);
}

async fn async_read_one() {
    log::info!("Read One started");
    sleep(Duration::from_secs(1)).await;
    log::info!("Read One completed")
}

async fn async_read_two() {
    log::info!("Read two started");
    sleep(Duration::from_secs(2)).await;
    log::info!("Read two completed");
}

I think this SO answer offers a good summary of the differences between the two: rust - When should you use tokio::join!() over tokio::spawn()? - Stack Overflow.

3 Likes

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.