Skip to content

Instantly share code, notes, and snippets.

@pfernandom
Last active November 9, 2018 21:42
Show Gist options
  • Save pfernandom/6c970ae4a4216a9ce1e6e4a65ec38c40 to your computer and use it in GitHub Desktop.
Save pfernandom/6c970ae4a4216a9ce1e6e4a65ec38c40 to your computer and use it in GitHub Desktop.
Using multiple threads in Rust. The tests are measured to quantify the impact of concurrency.
use std::thread;
use std::time::Duration;
use std::sync::mpsc;
use std::time::Instant;
fn start(label: &String) -> Instant {
println!("Start {}", label);
Instant::now()
}
fn end(now: Instant){
let elapsed = now.elapsed();
let sec = (elapsed.as_secs() as f64) + (elapsed.subsec_nanos() as f64 / 1000_000_000.0);
println!("Took {} seconds", sec);
}
fn test1(label: String, pause_time_millis: u64) {
let now = start(&label);
for i in 1..10 {
thread::sleep(Duration::from_millis(pause_time_millis));
let result = format!("hello-{}", i);
println!("Got: {}", result);
}
end(now);
}
fn test2(label: String, pause_time_millis: u64) {
let (tx, rx) = mpsc::channel();
let now = start(&label);
for i in 1..10 {
let tx1 = mpsc::Sender::clone(&tx);
thread::spawn(move || {
thread::sleep(Duration::from_millis(pause_time_millis));
let result = format!("hello-{}", i);
tx1.send(format!("hello-{}", i)).unwrap();
result
});
}
drop(tx);
for received in rx {
println!("Got: {}", received);
}
end(now);
}
fn main() {
let pause_time_millis = 1000;
test1(String::from("No async"), pause_time_millis);
test2(String::from("Aync"), pause_time_millis);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment