Review Fixes. Thanks to @eholk

This commit is contained in:
Bene 2023-05-05 09:11:10 +02:00
parent 87ac3cbdd3
commit d4d750523a
3 changed files with 35 additions and 4 deletions

View File

@ -37,6 +37,7 @@ interprocess
IoBlocker
IOCP
IoObject
JoinHandle
kqueue
localhost
LocalExecutor
@ -103,4 +104,3 @@ wakeups
webpages
webserver
Woot
JoinHandle

View File

@ -20,4 +20,27 @@ async fn main() {
task::spawn(async move {process_request(&mut stream).await});
}
}
// ANCHOR_END: example
// ANCHOR_END: example
use std::time::Duration;
async fn my_task(time: Duration) {
println!("Hello from my_task with time {:?}", time);
task::sleep(time).await;
println!("Goodbye from my_task with time {:?}", time);
}
// ANCHOR: join_all
use futures::future::join_all;
async fn task_spawner(){
let tasks = vec![
task::spawn(my_task(Duration::from_secs(1))),
task::spawn(my_task(Duration::from_secs(2))),
task::spawn(my_task(Duration::from_secs(3))),
];
// If we do not await these tasks and the function finishes, they will be dropped
join_all(tasks).await;
}
// ANCHOR_END: join_all
#[test]
fn run_task_spawner() {
futures::executor::block_on(task_spawner());
}

View File

@ -1,7 +1,7 @@
# `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.
while it runs.
Say we have a web server that wants to accept connections without blocking the main thread.
To achieve this, we can use the `async_std::task::spawn` function to create and run a new task that handles the
@ -12,5 +12,13 @@ task once it's completed.
{{#include ../../examples/06_04_spawning/src/lib.rs:example}}
```
The `JoinHandle` returned by `spawn` implements the `Future` trait, so we can `.await` it to get the result of the task.
This will block the current task until the spawned task completes. If the task is not awaited, your program will
continue executing without waiting for the task, cancelling it if the function is completed before the task is finished.
```rust,edition2018
{{#include ../../examples/06_04_spawning/src/lib.rs:join_all}}
```
To communicate between the main task and the spawned task, we can use channels
provided by the used async runtime.
provided by the async runtime used.