pub mod barrier;
pub mod channel;
pub mod condvar;
pub mod mutex;
pub use channel::Channel;
pub use condvar::Condvar;
pub struct Mutex<T> {
value: crate::ptr::Ptr<T>,
pub mutex: mutex::Mutex,
}
impl<T> Clone for Mutex<T> {
fn clone(&self) -> Self {
Self {
value: self.value,
mutex: self.mutex.clone(),
}
}
}
impl<T> Mutex<T> {
pub fn new(value: T) -> Self {
Self {
value: crate::ptr::Ptr::new(value),
mutex: mutex::Mutex::new(),
}
}
pub fn lock(&self) -> MutexGuard<'_, T> {
self.mutex.lock();
MutexGuard {
mtx: self.mutex.clone(),
value: self.value.get(),
}
}
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
if self.mutex.try_lock() {
Some(MutexGuard {
mtx: self.mutex.clone(),
value: self.value.get(),
})
} else {
None
}
}
}
pub struct MutexGuard<'a, T> {
value: &'a mut T,
mtx: mutex::Mutex,
}
impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
self.mtx.unlock();
}
}
use std::ops::{Deref, DerefMut};
impl<T> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value
}
}
impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
self.value
}
}