|
| 1 | +// threads3.rs |
| 2 | +// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a hint. |
| 3 | + |
| 4 | +// I AM NOT DONE |
| 5 | + |
| 6 | +use std::sync::mpsc; |
| 7 | +use std::sync::Arc; |
| 8 | +use std::thread; |
| 9 | +use std::time::Duration; |
| 10 | + |
| 11 | +struct Queue { |
| 12 | + length: u32, |
| 13 | + first_half: Vec<u32>, |
| 14 | + second_half: Vec<u32>, |
| 15 | +} |
| 16 | + |
| 17 | +impl Queue { |
| 18 | + fn new() -> Self { |
| 19 | + Queue { |
| 20 | + length: 10, |
| 21 | + first_half: vec![1, 2, 3, 4, 5], |
| 22 | + second_half: vec![6, 7, 8, 9, 10], |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () { |
| 28 | + let qc = Arc::new(q); |
| 29 | + let qc1 = qc.clone(); |
| 30 | + let qc2 = qc.clone(); |
| 31 | + |
| 32 | + thread::spawn(move || { |
| 33 | + for val in &qc1.first_half { |
| 34 | + println!("sending {:?}", val); |
| 35 | + tx.send(*val).unwrap(); |
| 36 | + thread::sleep(Duration::from_secs(1)); |
| 37 | + } |
| 38 | + }); |
| 39 | + |
| 40 | + thread::spawn(move || { |
| 41 | + for val in &qc2.second_half { |
| 42 | + println!("sending {:?}", val); |
| 43 | + tx.send(*val).unwrap(); |
| 44 | + thread::sleep(Duration::from_secs(1)); |
| 45 | + } |
| 46 | + }); |
| 47 | +} |
| 48 | + |
| 49 | +fn main() { |
| 50 | + let (tx, rx) = mpsc::channel(); |
| 51 | + let queue = Queue::new(); |
| 52 | + let queue_length = queue.length; |
| 53 | + |
| 54 | + send_tx(queue, tx); |
| 55 | + |
| 56 | + let mut total_received: u32 = 0; |
| 57 | + for received in rx { |
| 58 | + println!("Got: {}", received); |
| 59 | + total_received += 1; |
| 60 | + } |
| 61 | + |
| 62 | + println!("total numbers received: {}", total_received); |
| 63 | + assert_eq!(total_received, queue_length) |
| 64 | +} |
0 commit comments