diff --git a/exercises/20_threads/threads3.rs b/exercises/20_threads/threads3.rs index 7bb37668..b0fe8658 100644 --- a/exercises/20_threads/threads3.rs +++ b/exercises/20_threads/threads3.rs @@ -15,9 +15,6 @@ impl Queue { } fn send_tx(q: Queue, tx: mpsc::Sender) { - // TODO: We want to send `tx` to both threads. But currently, it is moved - // into the first thread. How could you solve this problem? - // Destructure the Queue to move first_half and second_half independently let Queue { first_half, diff --git a/solutions/20_threads/threads3.rs b/solutions/20_threads/threads3.rs index 7ceefea0..b0fe8658 100644 --- a/solutions/20_threads/threads3.rs +++ b/solutions/20_threads/threads3.rs @@ -15,22 +15,28 @@ impl Queue { } fn send_tx(q: Queue, tx: mpsc::Sender) { - // Clone the sender `tx` first. - let tx_clone = tx.clone(); + // Destructure the Queue to move first_half and second_half independently + let Queue { + first_half, + second_half, + } = q; + + // Clone the sender so both threads can send to the same receiver + let tx1 = tx.clone(); + let tx2 = tx; + thread::spawn(move || { - for val in q.first_half { + for val in first_half { println!("Sending {val:?}"); - // Then use the clone in the first thread. This means that - // `tx_clone` is moved to the first thread and `tx` to the second. - tx_clone.send(val).unwrap(); + tx1.send(val).unwrap(); thread::sleep(Duration::from_millis(250)); } }); thread::spawn(move || { - for val in q.second_half { + for val in second_half { println!("Sending {val:?}"); - tx.send(val).unwrap(); + tx2.send(val).unwrap(); thread::sleep(Duration::from_millis(250)); } }); @@ -59,4 +65,4 @@ mod tests { received.sort(); assert_eq!(received, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); } -} +} \ No newline at end of file