#![allow(dead_code)]
use std::sync::{Arc, Barrier, mpsc};
use std::thread;
use std::time::{Duration, Instant};
use snare::{Sim, SimBuilder};
fn workload() -> Duration {
let start = Instant::now();
let threads: Vec<_> = (0..8u8)
.map(|n| {
thread::spawn(move || {
let mut keep = Vec::new();
for i in 0..2_000usize {
keep.push(vec![n; (i * 37) % 70_000]);
if keep.len() > 50 {
keep.drain(..25);
}
}
thread::sleep(Duration::from_millis(200));
})
})
.collect();
for thread in threads {
thread.join().unwrap();
}
thread::sleep(Duration::from_secs(2));
start.elapsed()
}
fn within<T: Send + 'static>(limit: Duration, f: impl FnOnce() -> T + Send + 'static) -> T {
let (tx, rx) = mpsc::channel();
thread::spawn(move || tx.send(f()).unwrap());
rx.recv_timeout(limit)
.unwrap_or_else(|_| panic!("still running after {limit:?}: a hook deadlocked"))
}
fn assert_costs_only_its_sleeps(elapsed: Duration, what: &str) {
assert!(
elapsed >= Duration::from_millis(2_200) && elapsed < Duration::from_millis(2_300),
"{what}: the workload took {elapsed:?} of sim time"
);
}
fn unmanaged_threads() {
let n = 4 * thread::available_parallelism().map_or(4, |n| n.get()) + 8;
let all = Arc::new(Barrier::new(n));
let threads: Vec<_> = (0..n)
.map(|i| {
let all = all.clone();
thread::spawn(move || {
let kept: Vec<Vec<u8>> = (0..64).map(|j| vec![1; 64 + (i + j) * 97]).collect();
all.wait();
drop(kept);
})
})
.collect();
for thread in threads {
thread.join().unwrap();
}
}
type NamedSim = (&'static str, fn() -> SimBuilder);
fn watched() -> SimBuilder {
Sim::builder().stuck_after(Duration::from_secs(60))
}
pub fn under_sims() {
within(Duration::from_secs(120), || {
let sims: [NamedSim; 3] = [
("free-running", watched),
("deterministic", || watched().deterministic()),
("free-running again", watched),
];
for (n, (name, sim)) in sims.into_iter().enumerate() {
if n == 1 {
unmanaged_threads();
}
assert_costs_only_its_sleeps(sim().build().run(workload), name);
}
let parallel: Vec<_> = (0..4)
.map(|_| {
thread::spawn(|| {
for _ in 0..3 {
assert_costs_only_its_sleeps(watched().build().run(workload), "parallel");
}
})
})
.collect();
for sims in parallel {
sims.join().unwrap();
}
});
}