changeset 10:7eb649571bc6

add async example
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Mon, 18 Jan 2021 13:22:06 +0900
parents aaba40049c28
children 34aba7ec9efc
files Cargo.toml src/async_test/Cargo.toml src/async_test/src/main.rs src/t16thread/src/main.rs
diffstat 4 files changed, 56 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- 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",
 ]
--- /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 <kono@ie.u-ryukyu.ac.jp>"]
+edition = "2018"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+futures = "0.3"
--- /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
--- 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