use crate::DropHandle;
use std::{
sync::{Arc, Barrier, Once},
time::Duration,
};
use tracing::Level;
fn init_tracing() {
static INIT: Once = Once::new();
INIT.call_once(|| {
let subscriber = tracing_subscriber::fmt()
.with_max_level(Level::TRACE)
.with_line_number(true)
.with_test_writer()
.finish();
tracing::subscriber::set_global_default(subscriber)
.expect("global tracing subscriber should only be initialized once");
});
}
async fn wait_for_arc_count<T: Send + Sync>(arc: &Arc<T>, expected: usize) {
tokio::time::timeout(Duration::from_secs(2), async {
while Arc::strong_count(arc) != expected {
tokio::task::yield_now().await;
}
})
.await
.unwrap_or_else(|_| {
panic!(
"timed out waiting for Arc strong_count: got {}, expected {expected}",
Arc::strong_count(arc)
)
});
}
#[tokio::test]
async fn test_drop_handle() {
init_tracing();
let arc_counter = Arc::new(String::from("counter"));
assert_eq!(Arc::strong_count(&arc_counter), 1);
let arc_counter_clone = arc_counter.clone();
let drop_handle: DropHandle = tokio::spawn(async move {
loop {
tokio::time::sleep(Duration::from_millis(
Arc::strong_count(&arc_counter_clone) as u64 * 100,
))
.await;
}
})
.into();
assert!(!drop_handle.is_finished());
assert_eq!(Arc::strong_count(&arc_counter), 2);
drop(drop_handle.clone());
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(!drop_handle.is_finished());
assert_eq!(Arc::strong_count(&arc_counter), 2);
drop(drop_handle);
wait_for_arc_count(&arc_counter, 1).await;
assert_eq!(Arc::strong_count(&arc_counter), 1);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_concurrent_drop_handle_drops() {
const THREAD_COUNT: usize = 64;
init_tracing();
let counter = Arc::new(());
let task_counter = counter.clone();
let drop_handle: DropHandle = tokio::spawn(async move {
loop {
let _ = &task_counter;
tokio::time::sleep(Duration::from_secs(1)).await;
}
})
.into();
assert_eq!(Arc::strong_count(&counter), 2);
let clones: Vec<_> = (0..THREAD_COUNT).map(|_| drop_handle.clone()).collect();
let barrier = Barrier::new(THREAD_COUNT + 1);
std::thread::scope(|scope| {
for handle in clones {
scope.spawn(|| {
barrier.wait();
drop(handle);
});
}
barrier.wait();
drop(drop_handle);
});
wait_for_arc_count(&counter, 1).await;
}