Files

60 lines
1.8 KiB
Rust
Raw Permalink Normal View History

//! Behaviour of `Throttle` / `throttle()`: bounded number of in-flight items.
use obipipeline::{Throttle, throttle};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
#[test]
fn throttle_yields_every_item_in_order() {
let items: Vec<u32> = throttle(0..10u32, 100).map(|t| t.item).collect();
assert_eq!(items, (0..10).collect::<Vec<_>>());
}
#[test]
fn in_flight_items_never_exceed_the_bound() {
const MAX: usize = 3;
let in_flight = Arc::new(AtomicUsize::new(0));
let peak = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for t in throttle(0..40u32, MAX) {
let now = in_flight.fetch_add(1, Ordering::SeqCst) + 1;
peak.fetch_max(now, Ordering::SeqCst);
let in_flight = Arc::clone(&in_flight);
handles.push(thread::spawn(move || {
thread::sleep(Duration::from_millis(2));
in_flight.fetch_sub(1, Ordering::SeqCst);
drop(t); // releases the slot
}));
}
for h in handles {
h.join().unwrap();
}
assert!(
peak.load(Ordering::SeqCst) <= MAX,
"peak {}",
peak.load(Ordering::SeqCst)
);
}
#[test]
fn acquire_guard_blocks_until_a_slot_is_released() {
let t = Arc::new(Throttle::new(1));
let g1 = t.acquire_guard();
let acquired = Arc::new(AtomicUsize::new(0));
let (t2, a2) = (Arc::clone(&t), Arc::clone(&acquired));
let h = thread::spawn(move || {
let _g = t2.acquire_guard();
a2.store(1, Ordering::SeqCst);
});
thread::sleep(Duration::from_millis(50));
assert_eq!(
acquired.load(Ordering::SeqCst),
0,
"second acquire must block"
);
drop(g1);
h.join().unwrap();
assert_eq!(acquired.load(Ordering::SeqCst), 1);
}