Rust thread, マルチスレッド #Rust
■ 概要:
前のRustの関連となり。
thread の初級的なメモとなります。
■ 環境
Rust
rustc 1.46.0
cargo 1.46.0
ubuntu 18.04
■ 参考サイト様
https://doc.rust-jp.rs/book/second-edition/ch16-01-threads.html
■ thread の操作
・thread の作成
use std::thread;
use std::time::Duration;
/*******************************/
/* main */
/*******************************/
fn main() {
println!("#-start");
thread::spawn(|| {
for i in 1..10 {
println!("[spawn] hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
thread::spawn で、スレッド作成。ラムダ関数内で、処理を実行
・メインスレッドは、for内の printで。番号を出力して終了
・実行
$ cargo run
Compiling hello v0.1.0 (/home/naka/work/rust/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.74s
Running `target/debug/hello`
#-start
hi number 1 from the main thread!
[spawn] hi number 1 from the spawned thread!
hi number 2 from the main thread!
[spawn] hi number 2 from the spawned thread!
hi number 3 from the main thread!
[spawn] hi number 3 from the spawned thread!
[spawn] hi number 4 from the spawned thread!
hi number 4 from the main thread!
[spawn] hi number 5 from the spawned thread!
スレッド開始されますが。メイン側が先に終了し。
スレッド処理が、完了する前に終了されています。
(正常に動作してないような書き方)
■ スレッド待機
・handle.join()呼び出しのためにメインスレッドは待機し、起動スレッド終了まで実行
fn main() {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("[spawn] hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
handle.join().unwrap();
}
・実行
$ cargo run
Compiling hello v0.1.0 (/home/naka/work/rust/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.15s
Running `target/debug/hello`
hi number 1 from the main thread!
[spawn] hi number 1 from the spawned thread!
[spawn] hi number 2 from the spawned thread!
hi number 2 from the main thread!
[spawn] hi number 3 from the spawned thread!
hi number 3 from the main thread!
[spawn] hi number 4 from the spawned thread!
hi number 4 from the main thread!
[spawn] hi number 5 from the spawned thread!
[spawn] hi number 6 from the spawned thread!
[spawn] hi number 7 from the spawned thread!
[spawn] hi number 8 from the spawned thread!
[spawn] hi number 9 from the spawned thread!
今度は、スレッド処理が最後まで。実行され
作成したスレッド出力と、メインスレッドの出力が混在で
並列処理しているような形になりました。
■ スレッドにデータを渡す
・move を使用すると、スレッド内で渡されたデータ
を使用する事が可能です。
fn main() {
let v = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", v);
});
handle.join().unwrap();
}
・実行
$ cargo run
Compiling hello v0.1.0 (/home/naka/work/rust/hello)
Finished dev [unoptimized + debuginfo] target(s) in 1.19s
Running `target/debug/hello`
Here's a vector: [1, 2, 3]
スレッド外の変数を、出力できました。
ここから先は
0字
Rust WebAssembly 開発の事例、ノウハウに関する記事を集めました。第2回 ■ 免責事項 / 注記 , 内容について動作確…
この記事が気に入ったらサポートをしてみませんか?