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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use std::fmt;
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{AtomicBool, Ordering};

use crossbeam_utils::Backoff;

pub use super::poison;

pub struct Mutex<T: ?Sized> 
{
    c_locked: AtomicBool,
    poison: poison::Flag,
    data: UnsafeCell<T>,
}

unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}

pub struct MutexGuard<'a, T: ?Sized + 'a> 
{
    lock: &'a Mutex<T>,
    poison: poison::Guard,
}

//impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}

impl<'mutex, T: ?Sized> MutexGuard<'mutex, T> 
{
    unsafe fn new(lock: &'mutex Mutex<T>) -> poison::LockResult<MutexGuard<'mutex, T>> 
    {
        poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
    }
}

impl<T: ?Sized> Deref for MutexGuard<'_, T> 
{
    type Target = T;

    fn deref(&self) -> &T 
    {
        unsafe { &*self.lock.data.get() }
    }
}

impl<T: ?Sized> DerefMut for MutexGuard<'_, T> 
{
    fn deref_mut(&mut self) -> &mut T 
    {
        unsafe { &mut *self.lock.data.get() }
    }
}

impl<T: ?Sized> Drop for MutexGuard<'_, T> 
{
    #[inline]
    fn drop(&mut self) 
    {
        self.lock.poison.done(&self.poison);

        // unlock 
        self.lock.c_locked.store(false, Ordering::Release);
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> 
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> 
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        (**self).fmt(f)
    }
}

pub fn guard_poison<'a, T: ?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag 
{
    &guard.lock.poison
}

impl<T> Mutex<T> 
{
    pub fn new(t: T) -> Mutex<T> 
    {
        Mutex 
        {
            c_locked: AtomicBool::new(false),
            poison: poison::Flag::new(),
            data: UnsafeCell::new(t),
        }
    }

    pub fn unlock(guard: MutexGuard<'_, T>) 
    {
        drop(guard);
    }
}

impl<T: ?Sized> Mutex<T> 
{
    pub fn lock(&self) -> poison::LockResult<MutexGuard<'_, T>> 
    {
        let backoff = Backoff::new();

        // try lock
        while self.c_locked.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        return unsafe{ MutexGuard::new(self) };
    }

    pub fn try_lock(&self) -> poison::TryLockResult<MutexGuard<'_, T>> 
    {
        unsafe 
        {
            if self.c_locked.load(Ordering::Acquire) == true
            {
                Err(poison::TryLockError::WouldBlock)
            } 
            else 
            {
                let backoff = Backoff::new();

                // try lock
                while self.c_locked.swap(true, Ordering::Acquire) == true
                {
                    backoff.snooze();
                }
                
                Ok( MutexGuard::new(self)? )
            }
        }
    }

    pub fn is_poisoned(&self) -> bool 
    {
        self.poison.get()
    }

    pub fn into_inner(self) -> poison::LockResult<T>
    where T: Sized,
    {
        let data = self.data.into_inner();
        poison::map_result(self.poison.borrow(), |_| data)
    }

    pub fn get_mut(&mut self) -> poison::LockResult<&mut T> 
    {
        let data = self.data.get_mut();
        poison::map_result(self.poison.borrow(), |_| data)
    }
}


impl<T> From<T> for Mutex<T> 
{
    fn from(t: T) -> Self 
    {
        Mutex::new(t)
    }
}

impl<T: ?Sized + Default> Default for Mutex<T> 
{
    fn default() -> Mutex<T> 
    {
        Mutex::new(Default::default())
    }
}

impl<T: ?Sized + fmt::Debug> fmt::Debug for Mutex<T> 
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        let mut d = f.debug_struct("Mutex");
        match self.try_lock() 
        {
            Ok(guard) => 
            {
                d.field("data", &&*guard);
            }
            Err(poison::TryLockError::Poisoned(err)) => 
            {
                d.field("data", &&**err.get_ref());
            }
            Err(poison::TryLockError::WouldBlock) => 
            {
                struct LockedPlaceholder;
                impl fmt::Debug for LockedPlaceholder {
                    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                        f.write_str("<locked>")
                    }
                }
                d.field("data", &LockedPlaceholder);
            }
        }

        d.field("poisoned", &self.poison.get());
        d.finish_non_exhaustive()
    }
}

//todo tests

#[test]
fn test1_rw()
{
    use std::time::Instant;
    
    let start1 = Instant::now();

    let rw: std::sync::Mutex<Vec<u32>> = std::sync::Mutex::new(vec![1]);

    let start = Instant::now();
    let w = rw.lock();
    let el = start.elapsed();
    println!("write: {:?}", el);

    let mut w = w.unwrap();
    w.push(2);

    drop(w);

    let mut w = rw.lock().unwrap();
    w.push(3);

    drop(w);

    let r = rw.lock().unwrap();

    let el = start1.elapsed();
    println!("finished: {:?}", el);

    for i in r.iter()
    {
        println!("{}", i);
    }

    let v = vec![1,2,3];
    assert_eq!(v, *r);
}

#[test]
fn test2()
{
    use std::thread;
    use std::sync::Arc;
    use std::time::Instant;

    let start1 = Instant::now();

    let rw: Arc<Mutex<Vec<u32>>> = Arc::new(Mutex::new(vec![1]));

    let c_rw = rw.clone();

    let c_rw2 = rw.clone();
    
    let r = rw.lock().unwrap();

    let handler = thread::spawn(move || {
        // thread code
        println!("waiting to write 2");
        let mut w = c_rw.lock().unwrap();
        w.push(2);

        println!("wrote 2");
        println!("2:> {:?}", c_rw);
        drop(w);
    });

    std::thread::sleep(std::time::Duration::from_millis(1));
    let handler2 = thread::spawn(move || {
        // thread code
        println!("waiting to write 3");
        let mut w = c_rw2.lock().unwrap();
        w.push(3);
        
        println!("wrote 3");

        println!("3:> {:?}", c_rw2);
        drop(w);
    });
    
    std::thread::sleep(std::time::Duration::from_millis(4));

    for i in r.iter()
    {
        println!("{}", i);
    }

    println!("1:> {:?}", rw);

    println!("releasing read!");


    drop(r);

    handler.join().unwrap();
    handler2.join().unwrap();


    let start = Instant::now();
    let r = rw.lock().unwrap();
    let el = start.elapsed();
    println!("read: {:?}", el);
    
    println!("pre 1:> {:?}", rw);

    for i in r.iter()
    {
        println!("{}", i);
    }
    let v = vec![1,2,3];
    assert_eq!(v, *r);

    drop(r);

    let el = start1.elapsed();
    println!("finished: {:?}", el);

    println!("1:> {:?}", rw);
}