#what's the difference between tokio or rayon vs. std-thread?

2 messages · Page 1 of 1 (latest)

muted stone
#

I searched all over the net and couldn't really find much info on why/when to use tokio/rayon/async-std over std::thread. It seems like they're about the same. I'm used to goroutine and wanted to know why are there many diff async crates and when to use which, what's the difference to write async codes? what's the best practices if any? Thanks

use std::thread;
use std::time;

fn test_thread_spawn() {
    let start = time::Instant::now();
    let handler = thread::spawn(|| {
        println!("slow_running_task");
        thread::sleep(time::Duration::from_secs(2));
        println!("slow_running_task done");
        return 10;
    });

    println!("another task");
    thread::sleep(time::Duration::from_secs(5));
    println!("another task done");

    let res = handler.join().unwrap();
    let finish = time::Instant::now();
    println!("{} {:02?}", res, finish.duration_since(start));
}

async fn test_tokio_spawn() -> anyhow::Result<()> {
    let start = time::Instant::now();
    let task = tokio::spawn(async {
        println!("slow_running_task");
        tokio::time::sleep(time::Duration::from_secs(2)).await;
        println!("slow_running_task done");
        return 10;
    });

    println!("another task");
    tokio::time::sleep(time::Duration::from_secs(5)).await;
    println!("another task done");

    let res = task.await?;
    let finish = time::Instant::now();
    println!("{} {:02?}", res, finish.duration_since(start));
    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    test_thread_spawn();
    println!("----------");
    test_tokio_spawn().await?;
    Ok(())
}
woeful hornet