summaryrefslogtreecommitdiffstats
path: root/tokio/src/sync/tests/loom_rwlock.rs
blob: 48d06e1d5f6d596045bd0c5fa0b92343fc531cdd (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use crate::sync::rwlock::*;

use loom::future::block_on;
use loom::thread;
use std::sync::Arc;

#[test]
fn concurrent_write() {
    let mut b = loom::model::Builder::new();

    b.check(|| {
        let rwlock = Arc::new(RwLock::<u32>::new(0));

        let rwclone = rwlock.clone();
        let t1 = thread::spawn(move || {
            block_on(async {
                let mut guard = rwclone.write().await;
                *guard += 5;
            });
        });

        let rwclone = rwlock.clone();
        let t2 = thread::spawn(move || {
            block_on(async {
                let mut guard = rwclone.write().await;
                *guard += 5;
            });
        });

        t1.join().expect("thread 1 write should not panic");
        t2.join().expect("thread 2 write should not panic");
        //when all threads have finished the value on the lock should be 10
        let guard = block_on(rwlock.read());
        assert_eq!(10, *guard);
    });
}

#[test]
fn concurrent_read_write() {
    let mut b = loom::model::Builder::new();

    b.check(|| {
        let rwlock = Arc::new(RwLock::<u32>::new(0));

        let rwclone = rwlock.clone();
        let t1 = thread::spawn(move || {
            block_on(async {
                let mut guard = rwclone.write().await;
                *guard += 5;
            });
        });

        let rwclone = rwlock.clone();
        let t2 = thread::spawn(move || {
            block_on(async {
                let mut guard = rwclone.write().await;
                *guard += 5;
            });
        });

        let rwclone = rwlock.clone();
        let t3 = thread::spawn(move || {
            block_on(async {
                let guard = rwclone.read().await;
                //at this state the value on the lock may either be 0, 5, or 10
                assert!(*guard == 0 || *guard == 5 || *guard == 10);
            });
        });

        t1.join().expect("thread 1 write should not panic");
        t2.join().expect("thread 2 write should not panic");
        t3.join().expect("thread 3 read should not panic");

        let guard = block_on(rwlock.read());
        //when all threads have finished the value on the lock should be 10
        assert_eq!(10, *guard);
    });
}