スレッド

Rustのスレッドは他の言語のスレッドと似た挙動をします:

use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("Count in thread: {i}!");
            thread::sleep(Duration::from_millis(5));
        }
    });

    for i in 1..5 {
        println!("Main thread: {i}");
        thread::sleep(Duration::from_millis(5));
    }
}
  • スレッドはすべてデーモンスレッドで、メインスレッドはそれらを待ちません。
  • スレッドパニックは互いに独立です。
    • パニックはペイロードを保持していることがあり、それはdowncast_refで展開可能です。

要点:

  • Notice that the thread is stopped before it reaches 10 — the main thread is not waiting.

  • let handle = thread::spawn(…)と後にhandle.join()を使って、スレッドが完了するのを待ってみてください。

  • スレッド内でパニックを引き起こしてみて、それがどのようにmainに影響しないかを観察してみてください。

  • handle.join()の返り値のResultを使って、パニックペイロードへのアクセスを得てみてください。 これはAnyについて話すのに良いタイミングです。