Skip to content

Commit a3b5278

Browse files
exdxmanyinsects
authored andcommitted
feat: add threads3.rs exercise
1 parent a3c4c1c commit a3b5278

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

exercises/threads/threads3.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
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+
}

info.toml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -918,6 +918,20 @@ If you've learned from the sample solutions, I encourage you to come
918918
back to this exercise and try it again in a few days to reinforce
919919
what you've learned :)"""
920920

921+
[[exercises]]
922+
name = "threads3"
923+
path = "exercises/threads/threads3.rs"
924+
mode = "compile"
925+
hint = """
926+
An alternate way to handle concurrency between threads is to use
927+
a mpsc (multiple producer, single consumer) channel to communicate.
928+
With both a sending end and a receiving end, it's possible to
929+
send values in one thread and receieve them in another.
930+
Multiple producers are possibile by using clone() to create a duplicate
931+
of the original sending end.
932+
See https://doc.rust-lang.org/book/ch16-02-message-passing.html for more info.
933+
"""
934+
921935
# MACROS
922936

923937
[[exercises]]

0 commit comments

Comments
 (0)