Rust-concurrency

提供:Dev Guides
移動先:案内検索

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* 関数は、スレッドの実行を短時間停止させ、別のスレッドを実行できるようにします。 スレッドはおそらく交代しますが、それは保証されません-オペレーティングシステムがスレッドをスケジュールする方法に依存します。 この実行では、生成されたスレッドからのprintステートメントがコードの最初に表示されていても、メインスレッドが最初に印刷されます。 さらに、生成されたスレッドが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()*メソッドの呼び出しのために、生成されたスレッドが完了するまで待機します。