# HG changeset patch # User Shinji KONO # Date 1610943726 -32400 # Node ID 7eb649571bc6c8dc71f2e1ddbeba62443f2d0501 # Parent aaba40049c280fa39e4e14f57324e96041f08d2f add async example diff -r aaba40049c28 -r 7eb649571bc6 Cargo.toml --- a/Cargo.toml Tue Jan 12 15:47:17 2021 +0900 +++ b/Cargo.toml Mon Jan 18 13:22:06 2021 +0900 @@ -14,4 +14,5 @@ "guessing", "src/t01guessing", "src/t16thread", + "src/async_test", ] diff -r aaba40049c28 -r 7eb649571bc6 src/async_test/Cargo.toml --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/async_test/Cargo.toml Mon Jan 18 13:22:06 2021 +0900 @@ -0,0 +1,10 @@ +[package] +name = "async_test" +version = "0.1.0" +authors = ["Shinji KONO "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +futures = "0.3" diff -r aaba40049c28 -r 7eb649571bc6 src/async_test/src/main.rs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/async_test/src/main.rs Mon Jan 18 13:22:06 2021 +0900 @@ -0,0 +1,41 @@ +use futures::executor::block_on; + +struct Song { + +} + +async fn learn_song() -> Song { + println!("learn"); + Song {} } +async fn sing_song(song: Song) { + println!("sing_song") +} +async fn dance() { + println!("dance"); +} + +async fn learn_and_sing() { + // Wait until the song has been learned before singing it. + // We use `.await` here rather than `block_on` to prevent blocking the + // thread, which makes it possible to `dance` at the same time. + let song = learn_song().await; + sing_song(song).await; +} + +async fn async_main() { + let f1 = learn_and_sing(); + let f2 = dance(); + + // `join!` is like `.await` but can wait for multiple futures concurrently. + // If we're temporarily blocked in the `learn_and_sing` future, the `dance` + // future will take over the current thread. If `dance` becomes blocked, + // `learn_and_sing` can take back over. If both futures are blocked, then + // `async_main` is blocked and will yield to the executor. + futures::join!(f1, f2); +} + +fn main() { + let m = async_main(); + println!("waiting"); + block_on(m); +} \ No newline at end of file diff -r aaba40049c28 -r 7eb649571bc6 src/t16thread/src/main.rs --- a/src/t16thread/src/main.rs Tue Jan 12 15:47:17 2021 +0900 +++ b/src/t16thread/src/main.rs Mon Jan 18 13:22:06 2021 +0900 @@ -28,9 +28,9 @@ thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); // without this, some data are dropped - // main1(); - // t16thread::mpsc_test::mainm(); - // t16thread::mpsc_test::mainc(); - // t16thread::racecondition::mainr(); + main1(); + t16thread::mpsc_test::mainm(); + t16thread::mpsc_test::mainc(); + t16thread::racecondition::mainr(); t16thread::racecondition::mainu(); } \ No newline at end of file