「 Rust 1.39.0 の async/await をはよ覚えないと……☆」
# Rustをバージョンアップさせるなら☆(^~^)
cd C:\Users\むずでょ\.cargo\bin
rustup update
Async-await on stable Rust!
rust-lang/rfcs
async/.await Primer
async fn hello_world() {
println!("hello, world!");
}
「 非同期処理したい関数の頭に async 修飾するのが Rust のやり方らしいぜ☆」
fn main() {
let future = hello_world(); // Nothing is printed
}
「 同期処理も、非同期処理も、関数呼び出しの見た目は同じだぜ☆
ただし、 async が付いた関数は 本体が実行されるのではなく、
future オブジェクトを返すぜ☆」
https://crates.io/search?q=futures
Cargo.toml:
[dependencies]
futures = "0.3.1"
use futures::executor::block_on;
「 future オブジェクトは標準では実行できないので、クレートを使う☆」
block_on(future); // `future` is run and "hello, world!" is printed
Synchronized:
fn main() {
println!("hello, world!");
}
Asyncronized:
use futures::executor::block_on;
async fn hello_world() {
println!("hello, world!");
}
fn main() {
let future = hello_world(); // Nothing is printed
block_on(future); // `future` is run and "hello, world!" is printed
}
「 同期処理と、非同期処理で、それほどプログラマーの 負担は増えないな☆」
// cd C:\Users\むずでょ\source\repos\practice-rust\async-await
// cargo check --example join
// cargo build --example join
// cargo run --example join
//
// See also:
// https://crates.io/
use futures::executor::block_on;
async fn say_apple() {
println!("apple!");
}
async fn say_banana() {
println!("banana!");
}
async fn say_mix_juice() {
// こう書いても順次に動きはするが……☆(^~^)
say_apple().await;
say_banana().await;
}
fn main() {
let future = say_mix_juice();
block_on(future);
}
「 非同期処理を順次実行しても嬉しくないよな☆
並列に動いてほしいときは……☆」
// cd C:\Users\むずでょ\source\repos\practice-rust\async-await
// cargo check --example join
// cargo build --example join
// cargo run --example join
//
// See also:
// https://crates.io/
use futures::executor::block_on;
use std::thread;
use std::time::Duration;
async fn say_apple() {
print!("app");
thread::sleep(Duration::from_secs(1));
println!("le!");
}
async fn say_banana() {
print!("ban");
thread::sleep(Duration::from_secs(1));
println!("ana!");
}
async fn say_cherry() {
print!("che");
thread::sleep(Duration::from_secs(1));
println!("rry!");
}
async fn say_mix_juice() {
say_apple().await;
say_banana().await;
say_cherry().await;
}
fn main() {
let future = say_mix_juice();
block_on(future);
}
「 ↑スリープするタイミングが 思ってるのと違う……☆
スリープは カレント・スレッドをスリープさせるが、
非同期処理の block_on が使ってる方のスレッドはスリープさせないんだろうか……☆?」
async fn say_mix_juice() {
/*
say_apple().await;
say_banana().await;
say_cherry().await;
*/
futures::join!(say_apple(), say_banana(), say_cherry());
}
「 うーむ、ドキュメントは async/await 構文周りの話しだけで
非同期処理は ライブラリを調べた方がいいのか……☆?」
<書きかけ>
Crieitは個人で開発中です。
興味がある方は是非記事の投稿をお願いします! どんな軽い内容でも嬉しいです。
なぜCrieitを作ろうと思ったか
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください!