-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
48 lines (41 loc) · 1.06 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
fn is_prime(n: usize) -> bool {
(2..n).all(|i| n % i != 0)
}
fn producer(tx: mpsc::SyncSender<usize>) -> thread::JoinHandle<()> {
thread::spawn(move || {
for i in 100_000_000.. {
tx.send(i).unwrap();
}
})
}
fn worker(id: u64, share_rx: Arc<Mutex<mpsc::Receiver<usize>>>) {
thread::spawn(move || loop {
{
let mut n = 0;
match share_rx.lock() {
Ok(rx) => match rx.try_recv() {
Ok(_n) => {
n = _n;
}
Err(_) => (),
},
Err(_) => (),
}
if n != 0 {
if is_prime(n) {
println!("worker {} found a prime: {}", id, n);
}
}
}
});
}
fn main() {
let (tx, rx) = mpsc::sync_channel(1024);
let share_rx = Arc::new(Mutex::new(rx));
for i in 1..5 {
worker(i, share_rx.clone());
}
producer(tx).join().unwrap();
}