Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created December 21, 2022 14:42
Show Gist options
  • Save rust-play/f0a38b4264eb54a307b8193ecbc16479 to your computer and use it in GitHub Desktop.
Save rust-play/f0a38b4264eb54a307b8193ecbc16479 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
//use std::{thread, time::Duration};
//use rand::Rng;
#![feature(thread_id_value)]
use std::{thread, time::Duration, time::Instant};
use rand::Rng;
#[allow(unused_imports)]
use rayon::prelude::*;
fn do_work(x : u32) -> String {
let mut rng = rand::thread_rng(); // each thread have one
let s = rng.gen_range(100..1000);
let thread_id = thread::current().id();
let t = thread_id.as_u64();
thread::sleep(Duration::from_millis(s));
format!("w={} r={} working={}", t, x, s)
}
fn process_work_product(output : String) {
println!("{}", output);
}
fn main_new() {
// bit hacky, but lets set number of threads to 5
rayon::ThreadPoolBuilder::new().num_threads(4).build_global().unwrap();
let x = 0..10;
x.into_par_iter()
.map(do_work)
.for_each(process_work_product);
}
#[allow(unused)]
fn main_original() {
let mut hiv = Vec::new();
let (sender, receiver) = crossbeam_channel::unbounded();
// make workers
for t in 0..5 {
println!("Make worker {}", t);
let receiver = receiver.clone(); // clone for this thread
let handler = thread::spawn(move || {
let mut rng = rand::thread_rng(); // each thread have one
loop {
let r = receiver.recv();
match r {
Ok(x) => {
let s = rng.gen_range(100..1000);
thread::sleep(Duration::from_millis(s));
println!("w={} r={} working={}", t, x, s);
},
_ => { println!("No more work for {} --- {:?}.", t, r); break},
}
}
});
hiv.push(handler);
}
// Generate jobs
for x in 0..10 {
sender.send(x).expect("all threads hung up :(");
}
drop(sender);
// wait for jobs to finish.
println!("Wait for all threads to finish.");
for h in hiv {
h.join().unwrap();
}
println!("join() done. Work Finish.");
}
fn main() {
let start_new = Instant::now();
main_new();
let duration_new = start_new.elapsed();
let start_original = Instant::now();
main_original();
let duration_original = start_original.elapsed();
println!("\nmain_new duration: {:?}\n", duration_new);
println!("main_original duration: {:?}\n", duration_original);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment