Skip to content

Commit d4d7505

Browse files
Review Fixes. Thanks to @eholk
1 parent 87ac3cb commit d4d7505

File tree

3 files changed

+35
-4
lines changed

3 files changed

+35
-4
lines changed

ci/dictionary.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ interprocess
3737
IoBlocker
3838
IOCP
3939
IoObject
40+
JoinHandle
4041
kqueue
4142
localhost
4243
LocalExecutor
@@ -103,4 +104,3 @@ wakeups
103104
webpages
104105
webserver
105106
Woot
106-
JoinHandle

examples/06_04_spawning/src/lib.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,27 @@ async fn main() {
2020
task::spawn(async move {process_request(&mut stream).await});
2121
}
2222
}
23-
// ANCHOR_END: example
23+
// ANCHOR_END: example
24+
use std::time::Duration;
25+
async fn my_task(time: Duration) {
26+
println!("Hello from my_task with time {:?}", time);
27+
task::sleep(time).await;
28+
println!("Goodbye from my_task with time {:?}", time);
29+
}
30+
// ANCHOR: join_all
31+
use futures::future::join_all;
32+
async fn task_spawner(){
33+
let tasks = vec![
34+
task::spawn(my_task(Duration::from_secs(1))),
35+
task::spawn(my_task(Duration::from_secs(2))),
36+
task::spawn(my_task(Duration::from_secs(3))),
37+
];
38+
// If we do not await these tasks and the function finishes, they will be dropped
39+
join_all(tasks).await;
40+
}
41+
// ANCHOR_END: join_all
42+
43+
#[test]
44+
fn run_task_spawner() {
45+
futures::executor::block_on(task_spawner());
46+
}

src/06_multiple_futures/04_spawning.md

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# `Spawning`
22

33
Spawning allows you to run a new asynchronous task in the background. This allows us to continue executing other code
4-
while it is running.
4+
while it runs.
55

66
Say we have a web server that wants to accept connections without blocking the main thread.
77
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.
1212
{{#include ../../examples/06_04_spawning/src/lib.rs:example}}
1313
```
1414

15+
The `JoinHandle` returned by `spawn` implements the `Future` trait, so we can `.await` it to get the result of the task.
16+
This will block the current task until the spawned task completes. If the task is not awaited, your program will
17+
continue executing without waiting for the task, cancelling it if the function is completed before the task is finished.
18+
19+
```rust,edition2018
20+
{{#include ../../examples/06_04_spawning/src/lib.rs:join_all}}
21+
```
22+
1523
To communicate between the main task and the spawned task, we can use channels
16-
provided by the used async runtime.
24+
provided by the async runtime used.

0 commit comments

Comments
 (0)