The intended solution for 02_spawn spawns a task for each listener and within that task, spawns another task every time the listener accepts a connection.
// inside the loop of the helper function
let (mut socket, _) = listener.accept().await?;
tokio::spawn(async move {
let (mut reader, mut writer) = socket.split();
tokio::io::copy(&mut reader, &mut writer).await.unwrap();
});
For 03_runtime however, the solution does not spawn a new task.
let (mut socket, _) = listener.accept().await.unwrap();
let (_reader, mut writer) = socket.split();
writer
.write_all(format!("{}", reply).as_bytes())
.await
.unwrap();
If I understand the exercise correctly, this would block the listener until the response is finished.
I would think the solution should be something like
let (mut socket, _) = listener.accept().await.unwrap();
let reply = reply.clone(); /* reply: Arc<T>, so cloneable */
tokio::spawn(async move {
let (_, mut writer) = socket.split();
writer
.write_all(format!("{}", reply).as_bytes())
.await
.unwrap();
});
On a tangential note, it took me quite a while until I tread Arc because I assumed that the solution would not require us to add use std::sync::Arc ourselves.
Perhaps it would be a good idea to add this difficulty at an earlier time instead.
The intended solution for
02_spawnspawns a task for each listener and within that task, spawns another task every time the listener accepts a connection.For
03_runtimehowever, the solution does not spawn a new task.If I understand the exercise correctly, this would block the listener until the response is finished.
I would think the solution should be something like
On a tangential note, it took me quite a while until I tread
Arcbecause I assumed that the solution would not require us to adduse std::sync::Arcourselves.Perhaps it would be a good idea to add this difficulty at an earlier time instead.