Rustももちろん並行処理ができて、そのロジックは他の言語と類似ですが、簡単なコードで確認。Rustのドキュメンtの並行処理を多少改変しています。
どこが改変かというと、スレッドを複数spawnした時の終了待ちをhandleを配列(handles)に入れて、配列からhandleを取り出して全ての終了を待つようにしています。GolangのWaitGroupに相当する機能はなさそうなので、
use std::thread;
use std::time::Duration;
fn main() {
let mut handles = Vec::new();
for i in 0..3 {
let handle = thread::spawn(move || {
for j in 1..10 {
println!("hi number {} {} from the spawned thread!", i, j);
thread::sleep(Duration::from_millis(1));
}
});
handles.push(handle);
}
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
for handle in handles {
handle.join().unwrap();
}
}
<実行結果>
hi number 1 1 from the spawned thread!
hi number 2 1 from the spawned thread!
hi number 1 from the main thread!
hi number 0 1 from the spawned thread!
hi number 1 2 from the spawned thread!
hi number 2 2 from the spawned thread!
hi number 2 from the main thread!
hi number 0 2 from the spawned thread!
hi number 1 3 from the spawned thread!
hi number 2 3 from the spawned thread!
hi number 0 3 from the spawned thread!
hi number 3 from the main thread!
hi number 1 4 from the spawned thread!
hi number 2 4 from the spawned thread!
hi number 0 4 from the spawned thread!
hi number 4 from the main thread!
hi number 1 5 from the spawned thread!
hi number 2 5 from the spawned thread!
hi number 0 5 from the spawned thread!
hi number 1 6 from the spawned thread!
hi number 0 6 from the spawned thread!
hi number 2 6 from the spawned thread!
hi number 0 7 from the spawned thread!
hi number 1 7 from the spawned thread!
hi number 2 7 from the spawned thread!
hi number 0 8 from the spawned thread!
hi number 1 8 from the spawned thread!
hi number 2 8 from the spawned thread!
hi number 0 9 from the spawned thread!
hi number 1 9 from the spawned thread!
hi number 2 9 from the spawned thread!
二重ループ処理の複数(三個)のスレッドが動作しています。もちろんスレッドの実行順序は指定できません。
admin