Async question about await and loop

Why in this code is it possible to directly proceed with the next iteration of the loop without waiting for
client.get("http://127.0.0.1:6379").send().await
to complete?

#![allow(unused)]

use mini_redis::client;
use std::{thread, time::Duration};
use tokio::{io::AsyncWriteExt, net::TcpListener, sync::mpsc};

#[tokio::main]
async fn main() {
    // 服务器
    let server = tokio::spawn(async move {
        let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();
        loop {
            let (mut socket, addr) = listener.accept().await.unwrap();

            tokio::spawn(async move {
                // 等待 5s 后处理请求
                thread::sleep(Duration::from_secs(5));

                let response_status = "HTTP/1.1 200 OK";
                let contents = "hello, world";
                let length = contents.len();
                let response =
                    format!("{response_status}\r\nContent-Length: {length}\r\n\r\n\n{contents}");

                socket.write_all(response.as_bytes()).await.unwrap();
            });
        }
    });

    // 客户端
    let (tx, mut rx) = mpsc::channel(32);
    let manager = tokio::spawn(async move {
        // let mut client = client::connect("127.0.0.1:6379").await.unwrap();
        let client = reqwest::Client::new();
        while let Some(task) = rx.recv().await {
            println!("{:#?}", "睡眠前");

            // let res = client.get("foo").await;
            let res = client.get("http://127.0.0.1:6379").send().await;

            println!("{:#?}", "睡眠后");
        }
    });

    // 发送任务至 任务管理器
    for _ in 0..10 {
        let tx2 = tx.clone();
        tx2.send(1).await;
    }

    manager.await.unwrap();
}

Because you are using a combination of a spawned task and a mpsc channel which will buffer your calls.

Btw, you shouldn't use std::thread::sleep in async code. Use tokio's sleep instead.

2 Likes

whether if using for _ in 0..10 means that there will be generate 10 combination of a spawned task

No. There will be a single spawned task, and 10 messages sent through the channel.

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.