1 use std::sync::Arc; 2 3 use async_std::prelude::*; 4 use async_std::sync::Mutex; 5 use async_std::task; 6 use futures::channel::mpsc; 7 8 #[cfg(not(target_os = "unknown"))] 9 use async_std::task::spawn; 10 #[cfg(target_os = "unknown")] 11 use async_std::task::spawn_local as spawn; 12 13 #[cfg(target_arch = "wasm32")] 14 wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); 15 16 #[test] 17 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] smoke()18fn smoke() { 19 task::block_on(async { 20 let m = Mutex::new(()); 21 drop(m.lock().await); 22 drop(m.lock().await); 23 }) 24 } 25 26 #[test] 27 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] try_lock()28fn try_lock() { 29 let m = Mutex::new(()); 30 *m.try_lock().unwrap() = (); 31 } 32 33 #[test] 34 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] into_inner()35fn into_inner() { 36 let m = Mutex::new(10); 37 assert_eq!(m.into_inner(), 10); 38 } 39 40 #[test] 41 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] get_mut()42fn get_mut() { 43 let mut m = Mutex::new(10); 44 *m.get_mut() = 20; 45 assert_eq!(m.into_inner(), 20); 46 } 47 48 #[test] 49 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] contention()50fn contention() { 51 task::block_on(async { 52 let (tx, mut rx) = mpsc::unbounded(); 53 54 let tx = Arc::new(tx); 55 let mutex = Arc::new(Mutex::new(0)); 56 let num_tasks = 10000; 57 58 let mut handles = Vec::new(); 59 for _ in 0..num_tasks { 60 let tx = tx.clone(); 61 let mutex = mutex.clone(); 62 63 handles.push(spawn(async move { 64 let mut lock = mutex.lock().await; 65 *lock += 1; 66 tx.unbounded_send(()).unwrap(); 67 drop(lock); 68 })); 69 } 70 71 for _ in 0..num_tasks { 72 rx.next().await.unwrap(); 73 } 74 75 for handle in handles.into_iter() { 76 handle.await; 77 } 78 79 dbg!("wait"); 80 81 let lock = mutex.lock().await; 82 assert_eq!(num_tasks, *lock); 83 }); 84 } 85