3日目の勉強
- Drop トレイトを実装した struct はライフタイムの終了とともにクローズされる
- Java で言うところの
try-with-resources
と考えれば良さそう
#[derive(Debug)]
struct ConnectionManager {
connection: usize,
}
impl Drop for ConnectionManager {
fn drop(&mut self) {
println!("Dropped!");
}
}
fn main() {
println!("start.");
{
let connect = ConnectionManager { connection: 10 };
}
println!("end.");
}
start.
Dropped!
end.
スレッド
- スレッド出てくるの早くない?
- 言語としてスレッド安全性を保つ仕組みがしっかりしているとのこと
スレッドの実装
use std::{thread, time::Duration};
fn print_10(x: &usize) {
for i in 1..11 {
println!("I'm thread {}. roop_count = {}.", x, i);
let duration = Duration::new(0, 100000);
std::thread::sleep(duration);
}
}
fn main() {
let mut handler = vec![];
for i in 1..6 {
let handle = thread::spawn(move || print_10(&i));
handler.push(handle);
}
for handle in handler {
let _ = handle.join();
}
}
所感
- Rust の 基本でいきなりマルチスレッドの話まで出てきて焦る
- スレッド間制御は別日に実施
多謝