在 Rust 编程中使用线程
我们知道,一个进程是一个正在运行的程序。操作系统维护和管理多个进程。这些进程在独立部分运行,这些独立部分称为线程。
Rust 提供了 1:1 线程的实现。它提供了不同的 API,用于处理线程创建、连接以及许多此类方法。
使用 spawn 创建新的线程
要在 Rust 中创建新线程,我们调用thread::spawn 函数,然后向其传递一个闭包,该闭包反过来又包含我们希望在新线程中运行的代码。
示例
考虑下面所示的示例
use std::thread; use std::time::Duration; fn main() { thread::spawn(|| { for i in 1..10 { println!("hey number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..3 { println!("hey number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } }
输出
hey number 1 from the main thread! hey number 1 from the spawned thread! hey number 2 from the main thread! hey number 2 from the spawned thread!
有可能会产生 spawn 的线程不运行的情况,为了处理这种情况,我们将从thread::spawn 返回的值存储在变量中。thread::spawn 的返回类型是 JoinHandle.
JoinHandle 是一个所有权值,当我们对它调用连接方法时,它将等到线程完成
示例
我们对上面显示的示例进行一些修改,如下所示
use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!("hey number {} from the spawned thread!", i); thread::sleep(Duration::from_millis(1)); } }); handle.join().unwrap(); for i in 1..5 { println!("hey number {} from the main thread!", i); thread::sleep(Duration::from_millis(1)); } }
输出
hey number 1 from the spawned thread! hey number 2 from the spawned thread! hey number 3 from the spawned thread! hey number 4 from the spawned thread! hey number 5 from the spawned thread! hey number 6 from the spawned thread! hey number 7 from the spawned thread! hey number 8 from the spawned thread! hey number 9 from the spawned thread! hey number 1 from the main thread! hey number 2 from the main thread!
广告