Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

failed to run two threads using #[tokio::main] macro

I am trying to understand how tokio runtime works, i created two runtimes(on purpose) using #[tokio::main] macro, the first should executes function a() and the second executes function b().

I am assuming that they should be both printing "im awake A" and "im awake B" simultaniosuly forever (since they are calling a function that has a loop async_task), however that is not the case, it only prints "im awake A".

since each runtime has its own thread pool; why they are not running in parallel?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

use std::thread;
fn main() {
    a();
    b();
}

#[tokio::main]
async fn a() {
    tokio::spawn(async move { async_task("A".to_string()).await });
}

pub async fn async_task(msg: String) {
    loop {
        thread::sleep(std::time::Duration::from_millis(1000));
        println!("im awake {}", msg);
    }
}
#[tokio::main]
async fn b() {
    tokio::spawn(async move { async_task("B".to_string()).await });
}

>Solution :

Calling a(); from the synchronous main function will block until a() finishes. Check out the documentation here: https://docs.rs/tokio/1.2.0/tokio/attr.main.html

#[tokio::main] 
async fn main() {
    println!("Hello world"); 
}

Equivalent code not using #[tokio::main]

  fn main() {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            println!("Hello world");
        }) }

To get your example to work, main() could also be async and spawn 2 threads that run a, b and wait for them to finish:

#[tokio::main]
async fn main() {
    let t1 = thread::spawn(|| {
        a();
    });
    let t2 = thread::spawn(|| {
        b();
    });

    t1.join().unwrap();
    t2.join().unwrap();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading