Commit 0a822c2
committed
// threads3.rs
//
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
// threads3.rs
//
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
struct Queue {
length: u32,
first_half: Vec<u32>,
second_half: Vec<u32>,
}
impl Queue {
fn new() -> Self {
Queue {
length: 10,
first_half: vec![1, 2, 3, 4, 5],
second_half: vec![6, 7, 8, 9, 10],
}
}
}
fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
// 克隆 Sender 用于第二个线程
let tx2 = tx.clone();
// 第一个线程使用原始 tx 发送 first_half
thread::spawn(move || {
for val in q.first_half {
println!("sending {:?}", val);
tx.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
// 第二个线程使用克隆的 tx2 发送 second_half
thread::spawn(move || {
for val in q.second_half {
println!("sending {:?}", val);
tx2.send(val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
}
fn main() {
let (tx, rx) = mpsc::channel();
let queue = Queue::new();
let queue_length = queue.length;
send_tx(queue, tx);
let mut total_received: u32 = 0;
// 接收所有数据直到达到预期长度
for received in rx {
println!("Got: {}", received);
total_received += 1;
if total_received == queue_length {
break;
}
}
println!("total numbers received: {}", total_received);
assert_eq!(total_received, queue_length)
}1 parent f1a534f commit 0a822c2
1 file changed
+12
-8
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
16 | | - | |
17 | 16 | | |
18 | 17 | | |
19 | 18 | | |
| |||
34 | 33 | | |
35 | 34 | | |
36 | 35 | | |
37 | | - | |
38 | | - | |
39 | | - | |
| 36 | + | |
| 37 | + | |
40 | 38 | | |
| 39 | + | |
41 | 40 | | |
42 | | - | |
| 41 | + | |
43 | 42 | | |
44 | | - | |
| 43 | + | |
45 | 44 | | |
46 | 45 | | |
47 | 46 | | |
48 | 47 | | |
| 48 | + | |
49 | 49 | | |
50 | | - | |
| 50 | + | |
51 | 51 | | |
52 | | - | |
| 52 | + | |
53 | 53 | | |
54 | 54 | | |
55 | 55 | | |
| |||
63 | 63 | | |
64 | 64 | | |
65 | 65 | | |
| 66 | + | |
66 | 67 | | |
67 | 68 | | |
68 | 69 | | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
69 | 73 | | |
70 | 74 | | |
71 | 75 | | |
| |||
0 commit comments