mirror of
https://github.com/Noratrieb/nuclear.git
synced 2026-01-14 15:55:02 +01:00
mutex
This commit is contained in:
parent
2d3b5f3c94
commit
25ac075ef1
3 changed files with 75 additions and 1 deletions
|
|
@ -1 +1,2 @@
|
|||
compile_error!("lol");
|
||||
mod linked_list;
|
||||
mod mutex;
|
||||
|
|
|
|||
18
src/linked_list.rs
Normal file
18
src/linked_list.rs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
use std::ptr;
|
||||
use std::sync::atomic::AtomicPtr;
|
||||
|
||||
pub struct LinkedList<T> {
|
||||
head: AtomicPtr<Node<T>>,
|
||||
}
|
||||
|
||||
struct Node<T> {
|
||||
next: AtomicPtr<Node<T>>,
|
||||
}
|
||||
|
||||
impl<T> LinkedList<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
head: AtomicPtr::new(ptr::null_mut()),
|
||||
}
|
||||
}
|
||||
}
|
||||
55
src/mutex.rs
Normal file
55
src/mutex.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
use std::cell::UnsafeCell;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
const INIT: u8 = 0;
|
||||
const ACQUIRED: u8 = 1;
|
||||
|
||||
struct Mutex<T> {
|
||||
value: UnsafeCell<T>,
|
||||
status: AtomicU8,
|
||||
}
|
||||
|
||||
impl<T> Mutex<T> {
|
||||
pub fn new(value: T) -> Self {
|
||||
Self {
|
||||
value,
|
||||
status: AtomicU8::new(INIT),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
|
||||
if self
|
||||
.status
|
||||
.compare_exchange(INIT, ACQUIRED, Ordering::Acquire, Ordering::Relaxed)
|
||||
{
|
||||
Some(MutexGuard { mutex: self })
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MutexGuard<'a, T> {
|
||||
mutex: &'a Mutex<T>,
|
||||
}
|
||||
|
||||
impl<'a, T> Deref for MutexGuard<'a, T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { &*self.mutex.value.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> DerefMut for MutexGuard<'a, T> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
unsafe { &mut *self.mutex.value.get() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T> Drop for MutexGuard<'a, T> {
|
||||
fn drop(&mut self) {
|
||||
self.mutex.status.store(INIT, Ordering::Release);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue