Marvis Lu
Marvis Lu

Reputation: 439

What is the difference between two tokio::spawn usages?

I’m currently learning Tokio from its official tutorial, and the following code is part of the tutorial: https://tokio.rs/tokio/tutorial/spawning

use mini_redis::{Connection, Frame};
use tokio::net::{TcpListener, TcpStream};

#[tokio::main]
async fn main() {
   let listener = TcpListener::bind("127.0.0.1:6379").await.unwrap();

   loop {
       let (socket, _) = listener.accept().await.unwrap();
       
       // Option 1
       // tokio::spawn(process(socket));

       // Option 2
       tokio::spawn(async move {
           process(socket).await;
       });
   }
}

async fn process(socket: TcpStream) {
   let mut connection = Connection::new(socket);

   if let Some(frame) = connection.read_frame().await.unwrap() {
       println!("GOT: {:?}", frame);
       let response = Frame::Error("unimplemented".to_string());
       connection.write_frame(&response).await.unwrap();
   }
}

I have the following question regarding tokio::spawn usage:

What is the difference between these two usages of tokio::spawn?

Both seem to compile and run fine, so I’m wondering if there’s any real difference in behavior or performance implications.

Would appreciate any insights or explanations. Thanks!

Upvotes: 0

Views: 32

Answers (0)

Related Questions