mirror of https://github.com/rust-lang/async-book
Added Spawning example
This commit is contained in:
parent
e224ead527
commit
6957e04fba
|
@ -0,0 +1,13 @@
|
|||
[package]
|
||||
name = "example_06_04_spawning"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
futures = "0.3"
|
||||
|
||||
[dependencies.async-std]
|
||||
version = "1.12.0"
|
||||
features = ["attributes"]
|
|
@ -0,0 +1,33 @@
|
|||
#![cfg(test)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
// ANCHOR: example
|
||||
use async_std::{task, net::TcpListener, net::TcpStream};
|
||||
use futures::AsyncWriteExt;
|
||||
|
||||
async fn process_request(stream: &mut TcpStream) -> Result<(), std::io::Error>{
|
||||
stream.write_all(b"HTTP/1.1 200 OK\r\n\r\n").await?;
|
||||
stream.write_all(b"Hello World").await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn main() {
|
||||
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
|
||||
loop {
|
||||
// Accept a new connection
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
// Now process this request without blocking the main loop
|
||||
task::spawn(async move {process_request(&mut stream).await});
|
||||
}
|
||||
}
|
||||
// ANCHOR_END: example
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[async_std::test]
|
||||
async fn run_example() {
|
||||
main().await
|
||||
}
|
||||
}
|
|
@ -10,6 +10,7 @@ members = [
|
|||
"05_02_iteration_and_concurrency",
|
||||
"06_02_join",
|
||||
"06_03_select",
|
||||
"06_04_spawning",
|
||||
"07_05_recursion",
|
||||
"09_01_sync_tcp_server",
|
||||
"09_02_async_tcp_server",
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
# `Spawning`
|
||||
|
||||
Spawning allows you to run a new asynchronous task in the background. This allows us to continue executing other code
|
||||
while it is running.
|
||||
|
||||
Say we have a webserver that wants to accept connections without blocking the main thread.
|
||||
We can do this by using the `async_std::task::spawn` function to spawn a new task that runs
|
||||
the connection handler. This function takes a future and returns a `JoinHandle` that can be
|
||||
used to await the result of the spawned task.
|
||||
|
||||
```rust,edition2018
|
||||
{{#include ../../examples/06_04_spawning/src/lib.rs:example}}
|
||||
```
|
|
@ -16,7 +16,7 @@
|
|||
- [Executing Multiple Futures at a Time](06_multiple_futures/01_chapter.md)
|
||||
- [`join!`](06_multiple_futures/02_join.md)
|
||||
- [`select!`](06_multiple_futures/03_select.md)
|
||||
- [TODO: Spawning]()
|
||||
- [Spawning](06_multiple_futures/04_spawning.md)
|
||||
- [TODO: Cancellation and Timeouts]()
|
||||
- [TODO: `FuturesUnordered`]()
|
||||
- [Workarounds to Know and Love](07_workarounds/01_chapter.md)
|
||||
|
|
Loading…
Reference in New Issue