在 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!
生成的线程有可能无法运行,为了处理这种情况,我们将从thread::spawn返回的值存储在一个变量中。thread::spawn的返回类型是JoinHandle。
一个JoinHandle是一家拥有价值,当我们调用其join方法,将等待它的线程完成
示例
让我们稍微修改上面显示的示例,如下所示:
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!