about summary refs log tree commit diff
path: root/library/std/src/sync/reentrant_lock/tests.rs
blob: d4c1d440c61093c762c813e2ab8371983289f064 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use super::{ReentrantLock, ReentrantLockGuard};
use crate::cell::RefCell;
use crate::sync::Arc;
use crate::thread;

#[test]
fn smoke() {
    let l = ReentrantLock::new(());
    {
        let a = l.lock();
        {
            let b = l.lock();
            {
                let c = l.lock();
                assert_eq!(*c, ());
            }
            assert_eq!(*b, ());
        }
        assert_eq!(*a, ());
    }
}

#[test]
fn is_mutex() {
    let l = Arc::new(ReentrantLock::new(RefCell::new(0)));
    let l2 = l.clone();
    let lock = l.lock();
    let child = thread::spawn(move || {
        let lock = l2.lock();
        assert_eq!(*lock.borrow(), 4950);
    });
    for i in 0..100 {
        let lock = l.lock();
        *lock.borrow_mut() += i;
    }
    drop(lock);
    child.join().unwrap();
}

#[test]
fn trylock_works() {
    let l = Arc::new(ReentrantLock::new(()));
    let l2 = l.clone();
    let _lock = l.try_lock();
    let _lock2 = l.try_lock();
    thread::spawn(move || {
        let lock = l2.try_lock();
        assert!(lock.is_none());
    })
    .join()
    .unwrap();
    let _lock3 = l.try_lock();
}

pub struct Answer<'a>(pub ReentrantLockGuard<'a, RefCell<u32>>);
impl Drop for Answer<'_> {
    fn drop(&mut self) {
        *self.0.borrow_mut() = 42;
    }
}