Created
May 21, 2024 01:12
-
-
Save robert-king/29345d97542c444507c5d7ccfa4f735f to your computer and use it in GitHub Desktop.
Using Rust Channels for Concurrent Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://youtu.be/zhF-L_BgCHo | |
use std::sync::{mpsc::channel, Arc, Mutex}; | |
use std::thread; | |
use std::time::Instant; | |
fn is_prime(n: i32) -> bool { | |
if n < 2 { | |
return false; | |
} | |
for i in 2..n { | |
if n % i == 0 { | |
return false; | |
} | |
} | |
true | |
} | |
const NUM_THREADS: usize = 10; | |
const MAX_PRIME: i32 = 300_000; | |
fn main() { | |
let now = Instant::now(); | |
let (sender, receiver) = channel(); | |
let mut thread_handles = Vec::with_capacity(NUM_THREADS); | |
for i in 0..=MAX_PRIME { | |
sender.send(i).ok(); | |
} | |
drop(sender); | |
let receiver = Arc::new(Mutex::new(receiver)); | |
for _ in 0..NUM_THREADS { | |
let receiver2 = Arc::clone(&receiver); | |
thread_handles.push(thread::spawn(move || { | |
let mut count = 0; | |
loop { | |
let r = receiver2.lock().unwrap(); | |
let maybe_x = r.recv().ok(); | |
drop(r); | |
if let Some(x) = maybe_x { | |
if is_prime(x) { | |
count += 1; | |
} | |
} else { | |
return count; | |
} | |
} | |
})); | |
} | |
let count = thread_handles | |
.into_iter() | |
.map(|t| t.join().unwrap()) | |
.sum::<i32>(); | |
println!("{count}"); | |
println!("Elapsed: {:.2?}", now.elapsed()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment