use std::collections::BTreeSet;
use std::sync::{Arc, Barrier};
use rusty_alloc::init::thread_id;
const READS: usize = 2_000_000;
#[test]
fn thread_id_is_stable_within_a_thread() {
let first = thread_id();
let mut distinct = BTreeSet::new();
for _ in 0..READS {
distinct.insert(thread_id());
}
assert_eq!(
distinct.len(),
1,
"thread_id() drifted within one thread: saw {distinct:?} (first read {first:#x}). \
On Apple Silicon this is the tpidr_el0-vs-tpidrro_el0 bug — the low 3 bits of \
tpidrro_el0 are the CPU number and must be masked."
);
}
#[test]
fn thread_id_is_unique_across_live_threads() {
const THREADS: usize = 16;
let barrier = Arc::new(Barrier::new(THREADS));
let handles: Vec<_> = (0..THREADS)
.map(|_| {
let b = Arc::clone(&barrier);
std::thread::spawn(move || {
let id = thread_id();
b.wait(); let mut distinct = BTreeSet::new();
for _ in 0..(READS / 8) {
distinct.insert(thread_id());
}
b.wait(); assert_eq!(distinct.len(), 1, "thread_id() drifted mid-thread");
assert_eq!(id, thread_id(), "thread_id() changed across the run");
id
})
})
.collect();
let ids: Vec<usize> = handles.into_iter().map(|h| h.join().unwrap()).collect();
let unique: BTreeSet<usize> = ids.iter().copied().collect();
assert_eq!(
unique.len(),
THREADS,
"thread_id() COLLIDED across live threads: {THREADS} threads produced only {} distinct \
ids ({ids:#x?}). Distinct live threads sharing an owner id is a heap-corruption bug — \
the local free path assumes exclusive ownership.",
unique.len()
);
assert!(!unique.contains(&0), "0 is the abandoned sentinel, never a live id");
}
#[test]
fn thread_id_matches_the_platform_thread_identity() {
let pairs: Vec<(usize, usize)> = (0..8)
.map(|_| {
std::thread::spawn(|| {
let os_id = rusty_alloc::prim::thread_id();
(thread_id(), os_id)
})
.join()
.unwrap()
})
.collect();
for (fast, os) in &pairs {
assert_ne!(*fast, 0, "fast-path thread_id() returned the 0 sentinel");
assert_ne!(*os, 0, "prim::thread_id() returned 0");
}
for i in 0..pairs.len() {
for j in (i + 1)..pairs.len() {
if pairs[i].1 == pairs[j].1 {
assert_eq!(
pairs[i].0, pairs[j].0,
"same OS thread identity mapped to different fast-path ids"
);
}
}
}
}