Skip to content

Solution for 08_futures/03_runtime is inconsistent with 08/02_spawn. #321

Description

@kimhanm

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions