非境界チャネル
mpsc::channel() を使うと、非境界かつ非同期のチャネルを取得できます:
// Copyright 2022 Google LLC // SPDX-License-Identifier: Apache-2.0 use std::sync::mpsc; use std::thread; use std::time::Duration; fn main() { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let thread_id = thread::current().id(); for i in 0..10 { tx.send(format!("Message {i}")).unwrap(); println!("{thread_id:?}: sent Message {i}"); } println!("{thread_id:?}: done"); }); thread::sleep(Duration::from_millis(100)); for msg in rx { println!("Main: got {msg}"); } }
- 非境界チャネルは、保留中のメッセージを格納するために必要なだけの領域を割り当てます。
send()メソッドは呼び出し元のスレッドをブロックしません。 - チャネルが閉じられている場合、
send()の呼び出しはエラーで失敗します(そのためResultを返します)。受信側がドロップされると、チャネルは閉じられます。