Why does Tokio single threaded flavor not provide any concurrency?

use std::{
    thread,
    time::{Duration, SystemTime},
};

#[tokio::main(flavor = "current_thread")]
async fn main() {
    let handle_1 = tokio::spawn(async move {
        loop {
            println!("{:?} Hello from 1", SystemTime::now());
            thread::sleep(Duration::from_millis(2000))
        }
    });
    let handle_2 = tokio::spawn(async move {
        loop {
            println!("{:?} Hello from 2", SystemTime::now());
            thread::sleep(Duration::from_millis(5000))
        }
    });
    handle_1.await.unwrap();
    handle_2.await.unwrap();
}

(Playground)

Output

SystemTime { tv_sec: 1719896401, tv_nsec: 253252588 } Hello from 1
SystemTime { tv_sec: 1719896403, tv_nsec: 253411156 } Hello from 1
SystemTime { tv_sec: 1719896405, tv_nsec: 253504834 } Hello from 1
SystemTime { tv_sec: 1719896407, tv_nsec: 253627641 } Hello from 1
SystemTime { tv_sec: 1719896409, tv_nsec: 253785910 } Hello from 1
SystemTime { tv_sec: 1719896411, tv_nsec: 254074102 } Hello from 1
SystemTime { tv_sec: 1719896413, tv_nsec: 254410243 } Hello from 1
SystemTime { tv_sec: 1719896415, tv_nsec: 254574553 } Hello from 1
SystemTime { tv_sec: 1719896417, tv_nsec: 254955748 } Hello from 1
SystemTime { tv_sec: 1719896419, tv_nsec: 258449707 } Hello from 1
SystemTime { tv_sec: 1719896421, tv_nsec: 258703255 } Hello from 1
SystemTime { tv_sec: 1719896423, tv_nsec: 258839315 } Hello from 1
SystemTime { tv_sec: 1719896425, tv_nsec: 259088384 } Hello from 1
SystemTime { tv_sec: 1719896427, tv_nsec: 259232553 } Hello from 1
SystemTime { tv_sec: 1719896429, tv_nsec: 260017836 } Hello from 1

The classic beginner's mistake: you are using thread::sleep(), which blocks the thread. The runtime hasn't got a chance to context switch.

Use tokio's sleep instead. And read the relevant chapter in the async book.

8 Likes

Thanks, got same response from stackoverflow as well.

Please let us know (up front) when you cross post so there is not duplicated work in answering your question.

7 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.