diem_infallible/
mutex.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use std::sync::Mutex as StdMutex;
9
10pub use std::sync::MutexGuard;
11
12/// A simple wrapper around the lock() function of a std::sync::Mutex
13/// The only difference is that you don't need to call unwrap() on it.
14#[derive(Debug)]
15pub struct Mutex<T>(StdMutex<T>);
16
17impl<T> Mutex<T> {
18    /// creates mutex
19    pub fn new(t: T) -> Self { Self(StdMutex::new(t)) }
20
21    /// lock the mutex
22    pub fn lock(&self) -> MutexGuard<'_, T> {
23        self.0
24            .lock()
25            .expect("diem cannot currently handle a poisoned lock")
26    }
27}
28
29#[cfg(test)]
30mod tests {
31
32    use super::*;
33    use std::{sync::Arc, thread};
34
35    #[test]
36    fn test_diem_mutex() {
37        let a = 7u8;
38        let mutex = Arc::new(Mutex::new(a));
39        let mutex2 = mutex.clone();
40        let mutex3 = mutex.clone();
41
42        let thread1 = thread::spawn(move || {
43            let mut b = mutex2.lock();
44            *b = 8;
45        });
46        let thread2 = thread::spawn(move || {
47            let mut b = mutex3.lock();
48            *b = 9;
49        });
50
51        let _ = thread1.join();
52        let _ = thread2.join();
53
54        let _locked = mutex.lock();
55    }
56}