1use log::info;
2use std::error::Error;
3use std::sync::mpsc::{self, SendError};
4use std::thread;
5use std::time::Duration;
6
7pub fn move_test() {
8 let v = vec![1, 2, 3];
9 let handle = thread::spawn(move || {
10 info!("v contains {:?}", v);
11 });
12 handle.join().unwrap();
13}
14
15pub fn channel_test() -> Result<(), Box<dyn Error>> {
16 let (tx, rx) = mpsc::channel();
17 let vals = vec!["hello", "hi", "you", "world"];
18
19 let h = thread::spawn(move || -> Result<(), SendError<&str>> {
20 for val in vals {
21 info!("sent: {}", val);
22 tx.send(val)?;
23 thread::sleep(Duration::from_micros(1));
24 }
25 Ok(())
26 });
27 rx.iter().for_each(|recv| {
28 info!("received: {}", recv);
29 });
30 h.join().map_err(|_| "join error")??;
31 Ok(())
32}
33
34pub fn mpsc_test() -> Result<(), Box<dyn Error>> {
35 let (tx0, rx) = mpsc::channel();
36 let tx1 = tx0.clone();
37
38 let h0 = thread::spawn(move || -> Result<(), SendError<&str>> {
39 let vals = vec!["hello", "hi", "you", "world"];
40 for val in vals {
41 info!("thread 0 sent: {}", val);
42 tx0.send(val)?;
43 thread::sleep(Duration::from_micros(1));
44 }
45 Ok(())
46 });
47
48 let h1 = thread::spawn(move || -> Result<(), SendError<&str>> {
49 let vals = vec!["hello", "hi", "you", "world"];
50 for val in vals {
51 info!("thread 1 sent: {}", val);
52 tx1.send(val)?;
53 thread::sleep(Duration::from_micros(1));
54 }
55 Ok(())
56 });
57
58 rx.iter().for_each(|recv| {
59 info!("received: {}", recv);
60 });
61
62 h0.join().map_err(|_| "thread 0 join error")??;
63 h1.join().map_err(|_| "thread 1 join error")??;
64 Err("mpsc test err".into())
66}