use std::sync::{Mutex, MutexGuard, OnceLock, TryLockError};
use std::thread::ThreadId;
fn env_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
#[derive(Default)]
struct EnvScope {
generation: u64,
owner: Option<ThreadId>,
adopted: Vec<ThreadId>,
}
fn env_scope() -> &'static Mutex<EnvScope> {
static SCOPE: OnceLock<Mutex<EnvScope>> = OnceLock::new();
SCOPE.get_or_init(|| Mutex::new(EnvScope::default()))
}
fn lock_env_scope() -> MutexGuard<'static, EnvScope> {
match env_scope().lock() {
Ok(scope) => scope,
Err(poisoned) => poisoned.into_inner(),
}
}
fn open_env_scope() {
let mut scope = lock_env_scope();
scope.generation = scope.generation.wrapping_add(1);
scope.owner = Some(std::thread::current().id());
scope.adopted.clear();
}
fn current_thread_owns_contended_env_lock() -> bool {
let scope = lock_env_scope();
let current = std::thread::current().id();
scope.owner == Some(current) || scope.adopted.contains(¤t)
}
#[derive(Clone, Copy, Debug)]
pub struct EnvScopeTicket {
generation: u64,
}
impl EnvScopeTicket {
pub fn generation(&self) -> u64 {
self.generation
}
}
pub fn current_env_scope_generation() -> Option<u64> {
let scope = lock_env_scope();
let current = std::thread::current().id();
if scope.owner == Some(current) || scope.adopted.contains(¤t) {
Some(scope.generation)
} else {
None
}
}
pub fn env_scope_ticket() -> Option<EnvScopeTicket> {
let scope = lock_env_scope();
let current = std::thread::current().id();
(scope.owner == Some(current) || scope.adopted.contains(¤t)).then_some(EnvScopeTicket {
generation: scope.generation,
})
}
pub fn join_env_scope(ticket: Option<EnvScopeTicket>) -> Option<EnvScopeMembership> {
let ticket = ticket?;
let mut scope = lock_env_scope();
if scope.owner.is_none() || scope.generation != ticket.generation {
return None;
}
let thread = std::thread::current().id();
if !scope.adopted.contains(&thread) {
scope.adopted.push(thread);
}
Some(EnvScopeMembership {
generation: ticket.generation,
thread,
})
}
pub struct EnvScopeMembership {
generation: u64,
thread: ThreadId,
}
impl Drop for EnvScopeMembership {
fn drop(&mut self) {
let mut scope = lock_env_scope();
if scope.generation == self.generation {
scope.adopted.retain(|thread| *thread != self.thread);
}
}
}
pub struct TestEnvLock {
_guard: MutexGuard<'static, ()>,
}
impl Drop for TestEnvLock {
fn drop(&mut self) {
let mut scope = lock_env_scope();
if scope.owner == Some(std::thread::current().id()) {
scope.owner = None;
scope.adopted.clear();
}
}
}
pub fn lock_test_env() -> TestEnvLock {
let guard = match env_lock().lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
open_env_scope();
TestEnvLock { _guard: guard }
}
pub fn with_test_env_lock<T>(read: impl FnOnce() -> T) -> T {
if current_thread_owns_contended_env_lock() {
return read();
}
let _guard = lock_test_env();
read()
}
pub fn with_test_env_lock_if_uncontended<T>(read: impl FnOnce() -> T) -> T {
if current_thread_owns_contended_env_lock() {
return read();
}
match env_lock().try_lock() {
Ok(_guard) => read(),
Err(TryLockError::Poisoned(poisoned)) => {
let _guard = poisoned.into_inner();
read()
}
Err(TryLockError::WouldBlock) => read(),
}
}
pub fn current_thread_holds_test_env_lock() -> bool {
match env_lock().try_lock() {
Ok(guard) => {
drop(guard);
false
}
Err(TryLockError::Poisoned(poisoned)) => {
drop(poisoned.into_inner());
false
}
Err(TryLockError::WouldBlock) => current_thread_owns_contended_env_lock(),
}
}
#[cfg(test)]
mod tests {
use super::{lock_test_env, with_test_env_lock_if_uncontended};
use std::sync::mpsc;
use std::time::{Duration, Instant};
#[test]
fn adopted_worker_can_pass_only_its_live_environment_generation() {
let owner = lock_test_env();
let ticket = super::env_scope_ticket().unwrap();
let nested = std::thread::spawn(move || {
assert!(
super::env_scope_ticket().is_none(),
"foreign thread has no authority"
);
let _membership = super::join_env_scope(Some(ticket)).unwrap();
let child_ticket =
super::env_scope_ticket().expect("adopted worker can enroll its child");
std::thread::spawn(move || {
let _membership = super::join_env_scope(Some(child_ticket)).unwrap();
assert_eq!(
super::current_env_scope_generation(),
Some(child_ticket.generation())
);
assert_eq!(super::with_test_env_lock(|| 7), 7);
child_ticket
})
.join()
.unwrap()
})
.join()
.unwrap();
drop(owner);
let _next = lock_test_env();
assert!(
super::join_env_scope(Some(nested)).is_none(),
"old generation cannot join the next test"
);
}
#[test]
fn uncontended_read_returns_while_another_thread_holds_the_barrier() {
let (held_tx, held_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel::<()>();
let holder = std::thread::spawn(move || {
let _guard = lock_test_env();
held_tx.send(()).expect("announce that the barrier is held");
let _ = release_rx.recv_timeout(Duration::from_secs(30));
});
held_rx
.recv_timeout(Duration::from_secs(10))
.expect("holder thread must take the barrier");
let start = Instant::now();
let value = with_test_env_lock_if_uncontended(|| 7);
let elapsed = start.elapsed();
release_tx.send(()).ok();
holder.join().expect("holder thread");
assert_eq!(value, 7, "the read still runs, just unsynchronized");
assert!(
elapsed < Duration::from_secs(1),
"a contended read must not block; waited {elapsed:?}"
);
}
}