File tree Expand file tree Collapse file tree 3 files changed +35
-4
lines changed
examples/06_04_spawning/src Expand file tree Collapse file tree 3 files changed +35
-4
lines changed Original file line number Diff line number Diff line change @@ -37,6 +37,7 @@ interprocess
3737IoBlocker
3838IOCP
3939IoObject
40+ JoinHandle
4041kqueue
4142localhost
4243LocalExecutor
@@ -103,4 +104,3 @@ wakeups
103104webpages
104105webserver
105106Woot
106- JoinHandle
Original file line number Diff line number Diff 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+ }
Original file line number Diff line number Diff line change 11# ` Spawning `
22
33Spawning 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
66Say we have a web server that wants to accept connections without blocking the main thread.
77To 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+
1523To 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 .
You can’t perform that action at this time.
0 commit comments