| 1 | // vim: tw=80 |
| 2 | |
| 3 | use std::{ |
| 4 | sync::atomic::{AtomicBool, Ordering::Relaxed}, |
| 5 | thread, |
| 6 | time, |
| 7 | }; |
| 8 | |
| 9 | use divbuf::*; |
| 10 | use lazy_static::lazy_static; |
| 11 | |
| 12 | lazy_static! { |
| 13 | pub static ref DBS: DivBufShared = DivBufShared::from(vec![0; 4096]); |
| 14 | pub static ref SHUTDOWN: AtomicBool = AtomicBool::new(false); |
| 15 | } |
| 16 | |
| 17 | fn readfunc() { |
| 18 | let mut losses: u64 = 0; |
| 19 | let mut wins: u64 = 0; |
| 20 | while !SHUTDOWN.load(Relaxed) { |
| 21 | if let Ok(db) = (DBS).try_const() { |
| 22 | let mut db0 = db.slice(0, 1024); |
| 23 | let db1 = db.slice(1024, 2048); |
| 24 | db0.unsplit(db1).unwrap(); |
| 25 | wins += 1; |
| 26 | } else { |
| 27 | losses += 1; |
| 28 | } |
| 29 | } |
| 30 | println!("reader won {} races and lost {}", wins, losses); |
| 31 | } |
| 32 | |
| 33 | fn writefunc() { |
| 34 | let mut losses: u64 = 0; |
| 35 | let mut wins: u64 = 0; |
| 36 | while !SHUTDOWN.load(Relaxed) { |
| 37 | if let Ok(mut dbm) = (DBS).try_mut() { |
| 38 | let dbm1 = dbm.split_off(2048); |
| 39 | dbm.unsplit(dbm1).unwrap(); |
| 40 | wins += 1; |
| 41 | } else { |
| 42 | losses += 1; |
| 43 | } |
| 44 | } |
| 45 | println!("writer won {} races and lost {}", wins, losses); |
| 46 | } |
| 47 | |
| 48 | /// Create a multitude of threads that each try to divide a common static |
| 49 | /// buffer. They run for a fixed time. Success happens if nobody panics. |
| 50 | #[test] |
| 51 | fn test_thread_race() { |
| 52 | let reader0 = thread::spawn(readfunc); |
| 53 | let reader1 = thread::spawn(readfunc); |
| 54 | let writer0 = thread::spawn(writefunc); |
| 55 | let writer1 = thread::spawn(writefunc); |
| 56 | thread::sleep(time::Duration::from_secs(1)); |
| 57 | SHUTDOWN.store(true, Relaxed); |
| 58 | reader0.join().unwrap(); |
| 59 | reader1.join().unwrap(); |
| 60 | writer0.join().unwrap(); |
| 61 | writer1.join().unwrap(); |
| 62 | } |