通过通道在rust传递消息

  1. Rust实现消息传递并发的主要工具是通道。通道由两部分组成,一部分是发送端,一部
    分是接收端,发送端用来发送消息,接收端用来接受消息。通过通道可以传递参数而不用过多考虑生命周期 ,发送端或者接收端任何一个被丢
    弃就可以认为通道被关闭
  2. 通道的介绍:
    (1). 通过mpsc::channel,创建通道,mpsc是多个生产者,单个消费者
    (2). 通过spmc::channel,创建通道,spmc是一个生产者,多个消费者
    (3). 创建通道后返回的是发送者和消费者,如:
1
2
let (tx,rx) = mpsc::channel();
let (tx,rx) = spmc::channel();
  1. 关于通道:
    (1). 发送者的send方法返回一个Result<T,E>,如果接收端已经被丢弃,将没有发送值的目标
    ,此时发送会返回错误
    (2). 接受者的recv返回值也是一个Result类型,当通道发送端关闭时,返回一个错误值
    (3). 接收端的recv方法会阻塞到有一个消息到来,我们也可以使用try_recv(),不会阻塞,会
    立即返回
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::thread;
use std::sync::mpsc;

fn main() {
//首先创建通道
let (tx,rx) = mpsc::channel();
//其次创建线程
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap(); //进行发送
})

let received = rx.recv().unwrap();//recv方法会一直等待,等待一个值接受
println!("Got: {}",received);
}

通道的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::thread;
use std::sync::mpsc;

fn main() {
let (tx,rx) = mpsc::channel();

thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
//报错
//println!("val = {}",val); //val被移动到通道里面了(调用send),之后不能使用
});

let re = rx.recv().unwrap();
println!("Got {}",re);
}

发送多个值的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use std::thread;
use std::sync::mpsc;
use std::time::Duration;

fn main() {
let (tx,rx) = mpsc::channel();

thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),

];

for val in vals {
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
//可以直接使用for循环接受
for recv in rx {
println!("Got {}",recv);
}
}

多个生产者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use std::thread;
use std::sync::mpsc;
use std::time::Duration;

fn main()
{ //生产者分别通过tx1和tx发送
//发送是交替进行的
let (tx,rx) = mpsc::channel();
let tx1 = mpsc::Sender::clone(&tx);//子线程2
//生产者1
thread::spawn(move || {
let vals = vec![
String::from("hi"),
String::from("from"),
String::from("the"),
String::from("thread"),
]

for val in vals {
tx1.send(val).unwrap();//使用子线程2
thread::sleep(Duration::from_secs(1));
}
});
//生产者2
thread::spawn(move || {
let vals = vec![
String::from("A"),
String::from("B"),
String::from("C"),
String::from("D"),
]

for val in vals {
tx.send(val).unwrap();//使用子线程1
thread::sleep(Duration::from_secs(1));
}
});

for rec in rx {
println!("Got {}",rec);
}
}