线程

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));
    }
}
  • 线程均为守护程序线程,主线程不会等待这些线程。
  • 线程紧急警报 (panic) 是彼此独立的。
    • 紧急警报可以携带载荷,并可以使用 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 了。