extern crate priomutex;
extern crate rand;
use priomutex::Mutex;
use rand::*;
use std::mem;
use std::sync::Arc;
use std::thread;
use std::time::*;
#[test]
fn test_in_order_locking() {
const N: usize = 10;
let mut rng = thread_rng();
let mut prios: Vec<usize> = (0..N).map(|_| rng.gen::<usize>()).collect();
let mutex = Arc::new(Mutex::new(Vec::new()));
let guard = mutex.lock(0).unwrap();
let mut tids = Vec::new();
for &prio in prios.iter() {
let mutex = mutex.clone();
tids.push(thread::spawn(move || {
let mut data = mutex.lock(prio).unwrap(); data.push(prio); }));
}
thread::sleep(Duration::from_millis(1000));
mem::drop(guard);
for t in tids { t.join().unwrap(); }
prios.sort();
let prios2 = mutex.lock(0).unwrap();
assert_eq!(prios, *prios2);
}
#[test]
fn test_each_takes_once() {
let h = Arc::new(Mutex::new(vec![]));
let mut tids = vec![];
for i in 0..5 {
let h = h.clone();
tids.push(thread::spawn(move|| {
let mut x = h.lock(10-i).unwrap();
thread::sleep(Duration::from_millis(10));
x.push(i);
}));
}
for tid in tids { tid.join().unwrap(); }
}
#[test]
fn test_no_unfair_advantage() {
let m1 = Arc::new(Mutex::new(0));
let m2 = m1.clone();
{
let mut g = m1.lock(0).unwrap(); thread::spawn(move|| { let mut g = m2.lock(0).unwrap(); thread::sleep(Duration::from_millis(1000)); *g += 1;
});
thread::sleep(Duration::from_millis(500)); *g += 1;
} for _ in 0..100 {
if m1.try_lock().is_ok() {
panic!("try_lock succeeded when there was a thread waiting!");
}
}
}
#[test]
fn test_single_thread() {
let mutex = Arc::new(Mutex::new(0u8));
let x = mutex.lock(0).unwrap();
mem::drop(x);
let x = mutex.lock(1).unwrap();
mem::drop(x);
let x = mutex.lock(2).unwrap();
mem::drop(x);
let x = mutex.lock(3).unwrap();
mem::drop(x);
let x = mutex.lock(4).unwrap();
mem::drop(x);
}