|
| 1 | +# Tasks |
| 2 | + |
| 3 | +Runtimes have the concept of a "Task", similar to a thread but much |
| 4 | +less resource-intensive. |
| 5 | + |
| 6 | +A Task has a single top-level Future which the executor polls to make progress. |
| 7 | +That future may have one or more nested futures that its `poll` method polls, |
| 8 | +corresponding loosely to a call stack. Concurrency is possible within a task by |
| 9 | +polling multiple child futures, such as racing a timer and an I/O operation. |
| 10 | + |
| 11 | +```rust,editable,compile_fail |
| 12 | +use tokio::io::{self, AsyncReadExt, AsyncWriteExt}; |
| 13 | +use tokio::net::TcpListener; |
| 14 | +
|
| 15 | +#[tokio::main] |
| 16 | +async fn main() -> io::Result<()> { |
| 17 | + let listener = TcpListener::bind("127.0.0.1:6142").await?; |
| 18 | + println!("listening on port 6142"); |
| 19 | +
|
| 20 | + loop { |
| 21 | + let (mut socket, addr) = listener.accept().await?; |
| 22 | +
|
| 23 | + println!("connection from {addr:?}"); |
| 24 | +
|
| 25 | + tokio::spawn(async move { |
| 26 | + if let Err(e) = socket.write_all(b"Who are you?\n").await { |
| 27 | + println!("socket error: {e:?}"); |
| 28 | + return; |
| 29 | + } |
| 30 | +
|
| 31 | + let mut buf = vec![0; 1024]; |
| 32 | + let reply = match socket.read(&mut buf).await { |
| 33 | + Ok(n) => { |
| 34 | + let name = std::str::from_utf8(&buf[..n]).unwrap().trim(); |
| 35 | + format!("Thanks for dialing in, {name}!\n") |
| 36 | + } |
| 37 | + Err(e) => { |
| 38 | + println!("socket error: {e:?}"); |
| 39 | + return; |
| 40 | + } |
| 41 | + }; |
| 42 | +
|
| 43 | + if let Err(e) = socket.write_all(reply.as_bytes()).await { |
| 44 | + println!("socket error: {e:?}"); |
| 45 | + } |
| 46 | + }); |
| 47 | + } |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +<details> |
| 52 | + |
| 53 | +Copy this example into your prepared `src/main.rs` and run it from there. |
| 54 | + |
| 55 | +* Ask students to visualize what the state of the example server would be with a |
| 56 | + few connected clients. What tasks exist? What are their Futures? |
| 57 | + |
| 58 | +* Refactor the async block into a function, and improve the error handling using `?`. |
| 59 | + |
| 60 | +</details> |
0 commit comments