Skip to main content

agent_tui/
sync_utils.rs

1//! Synchronization utilities with poison recovery
2//!
3//! This module provides helper functions for acquiring locks on Mutex and RwLock
4//! that automatically recover from poisoned state. Poison recovery allows the
5//! application to continue operating even if a thread panicked while holding a lock.
6
7use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
8
9/// Recover from a poisoned RwLock read guard
10pub fn rwlock_read_or_recover<T>(lock: &RwLock<T>) -> RwLockReadGuard<'_, T> {
11    lock.read().unwrap_or_else(|poisoned| {
12        eprintln!("Warning: recovering from poisoned rwlock (read)");
13        poisoned.into_inner()
14    })
15}
16
17/// Recover from a poisoned RwLock write guard
18pub fn rwlock_write_or_recover<T>(lock: &RwLock<T>) -> RwLockWriteGuard<'_, T> {
19    lock.write().unwrap_or_else(|poisoned| {
20        eprintln!("Warning: recovering from poisoned rwlock (write)");
21        poisoned.into_inner()
22    })
23}
24
25/// Recover from a poisoned Mutex
26pub fn mutex_lock_or_recover<T>(lock: &Mutex<T>) -> MutexGuard<'_, T> {
27    lock.lock().unwrap_or_else(|poisoned| {
28        eprintln!("Warning: recovering from poisoned mutex");
29        poisoned.into_inner()
30    })
31}