#issue with nested tokio tasks

13 messages · Page 1 of 1 (latest)

red berry
#

Here's a minimal example of an issue I'm having:

#[tokio::main]
async fn main() {
    tokio::spawn(async move {
        let mut counter = 0;
        loop {
            std::thread::sleep(std::time::Duration::from_secs_f32(1.));
            counter += 1;
            if counter <= 5 {
                println!("schedule {counter}");
                tokio::spawn(async move {
                    println!("execute  {counter}");
                });
            } else {
                println!("skip     {counter}");
            }
        }
    }).await.unwrap();
}

output is as follows:

schedule 1
schedule 2
execute  1
schedule 3
execute  2
schedule 4
execute  3
schedule 5
execute  4
skip     6
skip     7
skip     8
skip     9
skip     10
...

In this example, "execute 5" is never printed. Why?

frosty orbit
#

Probably because your program ends before then

#

Please don’t ever use thread::sleep in an async task

#

it’s very bad

#

It leads to bugs

red berry
#

the program is an infinite loop, it never ends

#

thread::sleep is here to provide a minimal example, real thing is a lot more complicated to fit in the post

frosty orbit
#

it just obscures the actual issue

#

?eval ```rs
#[tokio::main]
async fn main() {
tokio::spawn(async move {
let mut counter = 0;
loop {
tokio::time::sleep(std::time::Duration::from_secs_f32(1.)).await;
counter += 1;
if counter <= 5 {
println!("schedule {counter}");
tokio::spawn(async move {
println!("execute {counter}");
});
} else {
println!("skip {counter}");
}
}
}).await.unwrap();
}

void voidBOT
#
/playground/tools/entrypoint.sh: line 11:     8 Killed                  timeout --signal=KILL ${timeout} "$@"

schedule 1
execute  1
schedule 2
execute  2
schedule 3
execute  3
schedule 4
execute  4
schedule 5
execute  5```Playground timeout detected
red berry
#

with tokio sleep it works fine

frosty orbit
#

Oh well then you have it