Skip to content

Instantly share code, notes, and snippets.

@arkadijs
Created September 10, 2016 15:43
Show Gist options
  • Save arkadijs/5ad44a2a223223da48f8c010eee5ab74 to your computer and use it in GitHub Desktop.
Save arkadijs/5ad44a2a223223da48f8c010eee5ab74 to your computer and use it in GitHub Desktop.
Beauty of Rust
use std::char;
use std::collections::HashMap;
use std::thread;
use std::sync::{Arc, Barrier};
use std::sync::mpsc::{channel, Sender};
const NTHREADS: u32 = 5;
fn slow(n: u32) -> char {
thread::sleep_ms(n);
let chr = char::from_u32(n % 26 + 65).unwrap();
chr
}
fn main() {
println!("[start]");
// poor man's actor
let (mem_tx, mem_rx) = channel::<(u32, Sender<char>)>();
thread::spawn(move|| {
let mut mem = HashMap::new();
for (n, tx) in mem_rx.iter() {
let chr = *mem.entry(n).or_insert_with(|| { slow(n) });
tx.send(chr).unwrap();
}
});
for pass in 0..3 {
let barrier = Arc::new(Barrier::new((NTHREADS as usize) + 1));
for i in 0..NTHREADS {
let n = (i + 1) * 500;
let bc = barrier.clone();
let mem_txc = mem_tx.clone();
thread::spawn(move|| {
let (tx, rx) = channel::<char>();
mem_txc.send((n, tx)).unwrap();
let chr = rx.recv().unwrap();
println!("pass {}: slow({}) = {}", pass, n, chr);
bc.wait();
println!("[thread {} about to die]", i);
});
}
barrier.wait();
}
// join threads here
println!("[end]");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment