Rust 编程中的通道
通道是一种允许在两个或多个线程之间进行通信的媒介。Rust 提供异步通道,以实现线程之间的通信。
Rust 中的通道允许在两个端点之间进行单向通信。这两个端点是发送方和接收方。
示例
考虑如下所示的示例 −
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;
use std::thread;
static NTHREADS: i32 = 3;
fn main() {
let (tx, rx): (Sender, Receiver) = mpsc::channel();
let mut children = Vec::new();
for id in 0..NTHREADS {
let thread_tx = tx.clone();
let child = thread::spawn(move || {
thread_tx.send(id).unwrap();
println!("thread {} done", id);
});
children.push(child);
}
let mut ids = Vec::with_capacity(NTHREADS as usize);
for _ in 0..NTHREADS {
ids.push(rx.recv());
}
for child in children {
child.join().expect("oops! the child thread stopped working");
}
println!("{:?}", ids);
}在上方的代码中,我们试图通过一个通道将线程的 id 传递到另一个线程。
输出
当我们运行上述代码时,我们会看到以下输出
thread 0 done thread 1 done thread 2 done [Ok(0), Ok(1), Ok(2)]
该输出表明所有线程都完美工作,并且能够通过通道在它们之间实现通信。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP