在 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!
廣告