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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use std::cell::UnsafeCell;
use std::hint::spin_loop;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::AtomicU32;
use std::sync::atomic::Ordering::{Acquire, Relaxed, Release};

use atomic_wait::{wait, wake_one};

// Possible states for the mutex
static UNLOCKED: u32 = 0;
static LOCKED: u32 = 1;
static LOCKED_WITH_WAITERS: u32 = 2;

/// a primitive for mutual exclusion
pub struct Mutex<T> {
    state: AtomicU32,
    value: UnsafeCell<T>,
}

unsafe impl<T> Sync for Mutex<T> where T: Send {}

pub struct MutexGuard<'a, T> {
    pub(crate) mutex: &'a Mutex<T>,
}

impl<T> Deref for MutexGuard<'_, T> {
    type Target = T;
    fn deref(&self) -> &T {
        unsafe { &*self.mutex.value.get() }
    }
}

impl<T> DerefMut for MutexGuard<'_, T> {
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.mutex.value.get() }
    }
}

impl<T> Drop for MutexGuard<'_, T> {
    #[inline]
    fn drop(&mut self) {
        if self.mutex.state.swap(UNLOCKED, Release) == LOCKED_WITH_WAITERS {
            wake_one(&self.mutex.state);
        }
    }
}

impl<T> Mutex<T> {
    /// Creates a new mutex.
    ///
    /// # Examples
    /// ```
    /// use lib_wc::sync::Mutex;
    ///
    /// let mutex = Mutex::new(0);
    /// ```
    pub fn new(value: T) -> Self {
        Self {
            state: AtomicU32::new(UNLOCKED),
            value: UnsafeCell::new(value),
        }
    }

    /// Acquires a lock on the mutex, blocking the current thread until it is able to do so.
    ///
    /// This function returns a `MutexGuard` which will release the lock when dropped.
    ///
    /// # Examples
    /// ```
    ///   use lib_wc::sync::Mutex;
    ///
    ///   let mutex = Mutex::new(0);
    ///
    ///   {
    ///     let mut guard = mutex.lock();
    ///     *guard += 1;
    ///   } // The guard is dropped here, unlocking the mutex
    ///
    ///   {
    ///     let mut guard = mutex.lock();
    ///     *guard += 1;
    ///   } // The guard is dropped here, unlocking the mutex
    ///
    ///   assert_eq!(*mutex.lock(), 2);
    ///
    /// ```
    #[inline]
    pub fn lock(&self) -> MutexGuard<T> {
        if self
            .state
            .compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed)
            .is_err()
        {
            lock_contended(&self.state)
        }
        MutexGuard { mutex: self }
    }
}

#[cold]
fn lock_contended(state: &AtomicU32) {
    let mut spin_count = 0;

    while state.load(Relaxed) == LOCKED && spin_count < 100 {
        spin_count += 1;
        spin_loop()
    }

    if state
        .compare_exchange(UNLOCKED, LOCKED, Acquire, Relaxed)
        .is_ok()
    {
        return;
    }

    while state.swap(LOCKED_WITH_WAITERS, Acquire) != UNLOCKED {
        wait(state, LOCKED_WITH_WAITERS)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::thread::scope;

    use super::*;

    #[test]
    fn you_can_modify_the_value() {
        let m: Arc<Mutex<u8>> = Arc::new(Mutex::new(1));

        {
            *m.lock() += 1;
        }

        std::thread::spawn({
            let m = m.clone();
            move || {
                *m.lock() += 1;
            }
        })
        .join()
        .unwrap();

        let v = *m.lock();
        assert_eq!(3, v);
    }

    #[test]
    fn test_mutex() {
        let mutex = Arc::new(Mutex::new(0));

        scope(|s| {
            for _ in 0..10 {
                let mutex = mutex.clone();
                s.spawn(move || {
                    for _ in 0..1000 {
                        let mut guard = mutex.lock();
                        *guard += 1;
                    }
                });
            }
        });

        assert_eq!(mutex.lock().deref(), &10000);
    }
}