Skip to main content

v_shield/sync/
mutex.rs

1//! Mutex wrapper multiplataforma
2//!
3//! - `native`: `std::sync::Mutex`
4//! - `wasm`: `std::sync::Mutex` (WASM single-threaded, pero thread-safe para compatibilidad)
5//! - `async-tokio`: `tokio::sync::Mutex`
6
7#[cfg(all(feature = "native", not(feature = "async-tokio")))]
8pub use std::sync::Mutex;
9
10#[cfg(all(feature = "wasm", not(feature = "async-tokio")))]
11pub use std::sync::Mutex;
12
13#[cfg(feature = "async-tokio")]
14pub use tokio::sync::Mutex;
15
16#[cfg(test)]
17mod tests {
18    use super::Mutex;
19
20    #[test]
21    fn test_mutex_basic() {
22        let m = Mutex::new(42);
23        let guard = m.lock().unwrap();
24        assert_eq!(*guard, 42);
25        drop(guard);
26
27        let m2 = Mutex::new(vec![1, 2, 3]);
28        {
29            let mut g = m2.lock().unwrap();
30            g.push(4);
31        }
32        assert_eq!(*m2.lock().unwrap(), vec![1, 2, 3, 4]);
33    }
34
35    #[test]
36    fn test_mutex_arc() {
37        use std::sync::Arc;
38        let m = Arc::new(Mutex::new(0));
39        let m_clone = Arc::clone(&m);
40        let handle = std::thread::spawn(move || {
41            let mut g = m_clone.lock().unwrap();
42            *g += 1;
43        });
44        {
45            let mut g = m.lock().unwrap();
46            *g += 1;
47        }
48        handle.join().unwrap();
49        assert_eq!(*m.lock().unwrap(), 2);
50    }
51}