线程
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
对载荷进行解压缩。
- 紧急警报可以携带载荷,并可以使用
关键点:
-
请注意,线程在达到 10 之前就停止了,而主线程并 没有等待。
-
使用
let handle = thread::spawn(...)
和后面的handle.join()
等待 线程完成。 -
在线程中触发紧急警报,并注意这为何不会影响到
main
。 -
使用
handle.join()
的Result
返回值来获取对紧急警报 载荷的访问权限。现在有必要介绍一下Any
了。