comparison src/async_test/src/main.rs @ 10:7eb649571bc6

add async example
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Mon, 18 Jan 2021 13:22:06 +0900
parents
children 70ab6c2f7f6e
comparison
equal deleted inserted replaced
9:aaba40049c28 10:7eb649571bc6
1 use futures::executor::block_on;
2
3 struct Song {
4
5 }
6
7 async fn learn_song() -> Song {
8 println!("learn");
9 Song {} }
10 async fn sing_song(song: Song) {
11 println!("sing_song")
12 }
13 async fn dance() {
14 println!("dance");
15 }
16
17 async fn learn_and_sing() {
18 // Wait until the song has been learned before singing it.
19 // We use `.await` here rather than `block_on` to prevent blocking the
20 // thread, which makes it possible to `dance` at the same time.
21 let song = learn_song().await;
22 sing_song(song).await;
23 }
24
25 async fn async_main() {
26 let f1 = learn_and_sing();
27 let f2 = dance();
28
29 // `join!` is like `.await` but can wait for multiple futures concurrently.
30 // If we're temporarily blocked in the `learn_and_sing` future, the `dance`
31 // future will take over the current thread. If `dance` becomes blocked,
32 // `learn_and_sing` can take back over. If both futures are blocked, then
33 // `async_main` is blocked and will yield to the executor.
34 futures::join!(f1, f2);
35 }
36
37 fn main() {
38 let m = async_main();
39 println!("waiting");
40 block_on(m);
41 }