use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, Barrier};
use std::thread;
use mod_tempdir::NamedTempFile;
const THREADS: usize = 256;
#[test]
fn concurrent_named_temp_file_new_yields_unique_paths() {
let barrier = Arc::new(Barrier::new(THREADS));
let mut handles = Vec::with_capacity(THREADS);
for _ in 0..THREADS {
let b = Arc::clone(&barrier);
handles.push(thread::spawn(move || {
b.wait();
NamedTempFile::new().expect("NamedTempFile::new failed under contention")
}));
}
let files: Vec<NamedTempFile> = handles
.into_iter()
.map(|h| h.join().expect("worker thread panicked"))
.collect();
let paths: HashSet<PathBuf> = files.iter().map(|f| f.path().to_path_buf()).collect();
assert_eq!(
paths.len(),
THREADS,
"path collision under contention: {} unique paths for {THREADS} threads",
paths.len()
);
for f in &files {
assert!(
f.path().is_file(),
"NamedTempFile reports {:?} but the file is not on disk",
f.path()
);
}
}