通常channel都是搭配并行使用,没有使用并行就没有使用channel的意义
「别透过共享记忆体来沟通,而是透过沟通来共享记忆体」。没错Golang的口号在Rust也是通用
Rust标准函式库也有提供类似Golang的Channel函式
Channel函式会回传两个变数分别为发送者(transmitter)与接收者(receiver)
Channel可以多个发送者(transmitter),单一接收者(receiver)
藉由这两变数来传递讯息
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel(); // 建立新的channel,回传一个元组,拆成两个变数
thread::spawn(move || {
let val = String::from("hello word");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap(); // (Blocking)等到有资料才会继续往下
println!("{}", received);
}
channel如果要在同一个通道多个执行绪使用发送者(transmitter)时,会因为所有权的关系造成错误,所以可以用clone来制造多个发送者(transmitter)
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let tx1 = tx.clone(); // 复制发送者
let tx2 = tx.clone(); // 复制发送者
thread::spawn(move || {
let val = String::from("hello word tx");
tx.send(val).unwrap();
});
thread::spawn(move || {
let val = String::from("hello word tx1");
tx1.send(val).unwrap();
});
thread::spawn(move || {
let val = String::from("hello word tx2");
tx2.send(val).unwrap();
});
for received in rx {
println!("{}", received);
}
}
输出
hello word tx
hello word tx2
hello word tx1
虽然channel本身不支援多个接收者(receiver),但是可以利用上锁让多个执行序同时使用接收者
今天有新闻说北部某医院疫苗注射没有稀释到 各位夥伴我之前也是在北部某联医注射AZ结果院方给我少打剂量...
每本安卓课本的第1步 用程序码来走一次: 1-贴两个xml档-(代做) 2-看下面的logcat看过...
这篇会介绍图表套件Charts的功能 graphView.leftAxis.enabled = fa...
惨 ...
上一篇介绍 firestore CRUD 的各种方式,今天要来介绍进阶的查询资料方式,利用条件去过滤...