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
#![cfg_attr(feature = "nightly", feature(const_fn))]

use lock_api::{RawReentrantMutex, RawMutex, GetThreadId};

use std::fmt;
use std::mem::ManuallyDrop;
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::cell::{RefMut, RefCell};

pub struct LendableMutex<R, G, T: ?Sized> {
	raw: RawReentrantMutex<R, G>,
	data: RefCell<T>
}

unsafe impl<R, G, T: ?Sized> Send for LendableMutex<R, G, T> {}
unsafe impl<R, G, T: ?Sized> Sync for LendableMutex<R, G, T> {}

impl<R: RawMutex, G: GetThreadId, T: ?Sized> LendableMutex<R, G, T> {
	#[cfg(feature = "nightly")]
	pub const fn new(v: T) -> Self where T: Sized {
		Self {
			raw: RawReentrantMutex::INIT,
			data: RefCell::new(v)
		}
	}

	#[cfg(not(feature = "nightly"))]
	pub fn new(v: T) -> Self where T: Sized {
		Self {
			raw: RawReentrantMutex::INIT,
			data: RefCell::new(v)
		}
	}

	pub fn into_inner(self) -> T where T: Sized { self.data.into_inner() }

	#[track_caller]
	#[inline]
	fn guard(&self) -> LendableMutexGuard<'_, R, G, T> {
		LendableMutexGuard {
			mutex: self,
			refmut: ManuallyDrop::new(self.data.borrow_mut()),
			marker: PhantomData
		}
	}

	pub unsafe fn force_unlock(&self) {
		self.raw.unlock();
	}

	pub unsafe fn raw(&self) -> &RawReentrantMutex<R, G> { &self.raw }

	#[track_caller]
	pub fn lock<'a>(&'a self) -> LendableMutexGuard<'a, R, G, T> {
		self.raw.lock();
		self.guard()
	}

	#[track_caller]
	pub fn try_lock<'a>(&'a self) -> Option<LendableMutexGuard<'a, R, G, T>> {
		if self.raw.try_lock() {
			Some(self.guard())
		} else {
			None
		}
	}

}

pub struct LendableMutexGuard<'a, R: RawMutex, G: GetThreadId, T: ?Sized> {
	mutex: &'a LendableMutex<R, G, T>,
	refmut: ManuallyDrop<RefMut<'a, T>>,
	marker: PhantomData<(&'a mut T, R::GuardMarker)>
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> Deref for LendableMutexGuard<'a, R, G, T> {
	type Target = T;
	fn deref(&self) -> &T { &*self.refmut }
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> DerefMut for LendableMutexGuard<'a, R, G, T> {
	fn deref_mut(&mut self) -> &mut T { &mut *self.refmut }
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized + Debug> Debug for LendableMutexGuard<'a, R, G, T> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		Debug::fmt(&**self, f)
	}
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized + Display> Display for LendableMutexGuard<'a, R, G, T> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		Display::fmt(&**self, f)
	}
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> Drop for LendableMutexGuard<'a, R, G, T> {
	fn drop(&mut self) {
		unsafe {
			ManuallyDrop::drop(&mut self.refmut); // !! DROP THIS FIRST !!
			self.mutex.force_unlock();
		}
	}
}

impl<'a, R: RawMutex, G: GetThreadId, T: ?Sized> LendableMutexGuard<'a, R, G, T> {
	pub fn mutex(&self) -> &'a LendableMutex<R, G, T> { self.mutex }
	pub fn lend(&mut self, f: impl FnOnce()) {
		unsafe { ManuallyDrop::drop(&mut self.refmut); }
		let _defer = defer::defer(|| {
			self.refmut = ManuallyDrop::new(self.mutex.data.borrow_mut());
		});
		f();
	}
}

pub type PlLendableMutex<T> = LendableMutex<parking_lot::RawMutex, parking_lot::RawThreadId, T>;
pub type PlLendableMutexGuard<'a, T> = LendableMutexGuard<'a, parking_lot::RawMutex, parking_lot::RawThreadId, T>;

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

    #[test]
    fn basic_mutex() {
        let m = Arc::new(PlLendableMutex::new(0));
        let mut handles = Vec::new();
        for _ in 0..100 {
			let m2 = m.clone();
			handles.push(thread::spawn(move || {
				let mut l = m2.lock();
				*l += 1;
			}));
		}
        for h in handles { h.join().unwrap(); }
        assert_eq!(*m.lock(), 100);
    }

    #[test]
    fn stays_locked() {
        let m = Arc::new(PlLendableMutex::new(0));
        let mut handles = Vec::new();
        for _ in 0..100 {
			let m2 = m.clone();
			handles.push(thread::spawn(move || {
				println!("[{:?}] locking", thread::current().id());
				let mut l = m2.lock();
				println!("[{:?}] locked", thread::current().id());
				let old = *l;
				*l += 1;
				println!("[{:?}] lending", thread::current().id());
				l.lend(|| {
					println!("[{:?}] lent", thread::current().id());
					#[allow(deprecated)] thread::sleep_ms(100);
					let mut l2 = m2.lock();
					assert_eq!(*l2, old + 1);
					*l2 += 1;
					println!("[{:?}] end lend", thread::current().id());
				});
				assert_eq!(*l, old + 2);
				println!("[{:?}] end of thread", thread::current().id());
			}));
		}
        for h in handles { h.join().unwrap(); }
        assert_eq!(*m.lock(), 200);
    }
}