threads3.rs (1352B)
1 use std::{sync::mpsc, thread, time::Duration}; 2 3 struct Queue { 4 first_half: Vec<u32>, 5 second_half: Vec<u32>, 6 } 7 8 impl Queue { 9 fn new() -> Self { 10 Self { 11 first_half: vec![1, 2, 3, 4, 5], 12 second_half: vec![6, 7, 8, 9, 10], 13 } 14 } 15 } 16 17 fn send_tx(q: Queue, tx: mpsc::Sender<u32>) { 18 // TODO: We want to send `tx` to both threads. But currently, it is moved 19 // into the first thread. How could you solve this problem? 20 thread::spawn(move || { 21 for val in q.first_half { 22 println!("Sending {val:?}"); 23 tx.send(val).unwrap(); 24 thread::sleep(Duration::from_millis(250)); 25 } 26 }); 27 28 thread::spawn(move || { 29 for val in q.second_half { 30 println!("Sending {val:?}"); 31 tx.send(val).unwrap(); 32 thread::sleep(Duration::from_millis(250)); 33 } 34 }); 35 } 36 37 fn main() { 38 // You can optionally experiment here. 39 } 40 41 #[cfg(test)] 42 mod tests { 43 use super::*; 44 45 #[test] 46 fn threads3() { 47 let (tx, rx) = mpsc::channel(); 48 let queue = Queue::new(); 49 50 send_tx(queue, tx); 51 52 let mut received = Vec::with_capacity(10); 53 for value in rx { 54 received.push(value); 55 } 56 57 received.sort(); 58 assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); 59 } 60 }