Rust - 併發



在併發程式設計中,程式的不同部分獨立執行。另一方面,在並行程式設計中,程式的不同部分同時執行。隨著越來越多的計算機利用其多處理器優勢,這兩種模型都同等重要。

執行緒

我們可以使用執行緒來同時執行程式碼。在當前的作業系統中,已執行程式的程式碼在一個程序中執行,作業系統同時管理多個程序。在您的程式中,您還可以擁有同時執行的獨立部分。執行這些獨立部分的功能稱為執行緒。

建立執行緒

thread::spawn 函式用於建立新執行緒。spawn 函式接受閉包作為引數。閉包定義了執行緒應該執行的程式碼。以下示例從主執行緒列印一些文字,從新執行緒列印其他文字。

//import the necessary modules
use std::thread;
use std::time::Duration;

fn main() {
   //create a new thread
   thread::spawn(|| {
      for i in 1..10 {
         println!("hi number {} from the spawned thread!", i);
         thread::sleep(Duration::from_millis(1));
      }
   });
   //code executed by the main thread
   for i in 1..5 {
      println!("hi number {} from the main thread!", i);
      thread::sleep(Duration::from_millis(1));
   }
}

輸出

hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 4 from the main thread!

主執行緒列印從 1 到 4 的值。

注意 - 主執行緒結束後,新執行緒將停止。該程式的輸出每次可能略有不同。

thread::sleep 函式強制執行緒停止執行一小段時間,允許其他執行緒執行。執行緒可能會輪流執行,但這並非保證——這取決於作業系統如何排程執行緒。在這個執行中,主執行緒首先列印,即使來自派生執行緒的列印語句在程式碼中先出現。此外,即使派生執行緒被程式設計為列印到 9 的值,它在主執行緒關閉之前只執行到 5。

連線控制代碼

派生的執行緒可能沒有機會執行或完全執行。這是因為主執行緒很快就完成了。函式 spawn<F, T>(f: F) -> JoinHandlelt;T> 返回一個 JoinHandle。JoinHandle 上的 join() 方法等待關聯的執行緒完成。

use std::thread;
use std::time::Duration;

fn main() {
   let handle = thread::spawn(|| {
      for i in 1..10 {
         println!("hi number {} from the spawned thread!", i);
         thread::sleep(Duration::from_millis(1));
      }
   });
   for i in 1..5 {
      println!("hi number {} from the main thread!", i);
      thread::sleep(Duration::from_millis(1));
   }
   handle.join().unwrap();
}

輸出

hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 2 from the main thread!
hi number 3 from the spawned thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!

主執行緒和派生執行緒繼續切換。

注意 - 由於呼叫了 join() 方法,主執行緒等待派生執行緒完成。

廣告
© . All rights reserved.