Skip to content

Instantly share code, notes, and snippets.

Created November 18, 2017 02:08
Show Gist options
  • Save anonymous/5de97727aba9ee7333b8e48da83122a3 to your computer and use it in GitHub Desktop.
Save anonymous/5de97727aba9ee7333b8e48da83122a3 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
extern crate crossbeam;
extern crate rand;
use rand::Rng;
#[allow(unused)]
use std::sync::{RwLock, Mutex};
const ARRAY_LEN: usize = 1000;
const READS_PER_WRITE: u32 = 5;
// trait Lock {
// type ReadGuard: std::ops::Deref<Target=[i32; ARRAY_LEN];
// type WriteGuard: std::ops::DerefMut<Target=[i32; ARRAY_LEN]>;
// fn read(&self) -> ReadGuard;
// fn write(&self) -> WriteGuard;
// }
// impl Lock for Mutex<[i32, ARRAY_LEN]> {
// type ReadGuard =
// }
fn main() {
let m = RwLock::new([0u8; ARRAY_LEN]);
crossbeam::scope(|scope| {
for x in 0..20 {
let m = &m;
let mut v = Vec::new();
scope.spawn(move || {
let mut rng = rand::thread_rng();
let mut writes = 0;
let mut reads = 0;
for _ in 0..500000 {
let idx = rng.gen_range(0, ARRAY_LEN);
if rng.gen_weighted_bool(READS_PER_WRITE + 1) {
m.write().unwrap()[idx] = rng.gen();
writes += 1;
} else {
let value: u8 = m.read().unwrap()[idx];
if rng.gen_weighted_bool(READS_PER_WRITE * 25000) {
v.push(value);
}
reads += 1;
}
}
println!("thread {:2} reads: {} writes: {} results: {:?}", x, reads, writes, v);
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment