About async Why does the block in main thread affect the child threads

I am new to Rust. I used to think async is a program that runs in child threads, but when I run my code, the block in my main thread affects the child threads. I don't know what the problem is, and I hope you can help me.

async fn main() {
    let (tx,rx) = oneshot::channel();
    let srv = servers::sc_servers("",rx);
    for i in {1..10}{
    // signal::ctrl_c().await;
    // tx.send("stop");
pub async fn sc_servers(addr: &str,rx:tokio::sync::oneshot::Receiver<&str>) {
    // defining address for our service
    let mut listen_addr: SocketAddr = "[::1]:50051".parse().unwrap();
    if addr != "" {
        listen_addr = addr.parse().unwrap()
    /// 1.register server
    let srv_reg = RegisterCenterServer::default();

    println!("Scheduler Servers listening on {}", listen_addr);


    println!("sc here")

Get this result

There are two problems in your code:

  1. Async code is lazy
  2. Use of std::thread::sleep.

The first problem is that async code is lazy and does not start running until you .await it. If you want something to run in the background, you should instead use tokio::spawn.

// Start background task immediately.
let srv = tokio::spawn(servers::sc_servers("",rx));
for i in 1..10 {
// Sleep until spawned task exits.

The second problem is the use of std::thread::sleep (I can't see your import, but there's no .await so it must be the std one and not the sleep in Tokio). There's an in-depth explanation of why this is a problem here, and it also includes explanations of how to fix it.

Thanks for your help. It's not in the order I thought it would be. That would explain it all. Let me take a good look at your blog

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.