1 // Copyright 2023 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 use crate::NoPoisonMutex; 16 17 /// A mutual exclusion primitive useful for protecting shared data 18 pub struct Mutex<T>(spin::Mutex<T>); 19 20 impl<T> NoPoisonMutex<T> for Mutex<T> { 21 type MutexGuard<'a> = spin::MutexGuard<'a, T> where T: 'a; 22 lock(&self) -> Self::MutexGuard<'_>23 fn lock(&self) -> Self::MutexGuard<'_> { 24 self.0.lock() 25 } 26 try_lock(&self) -> Option<Self::MutexGuard<'_>>27 fn try_lock(&self) -> Option<Self::MutexGuard<'_>> { 28 self.0.try_lock() 29 } 30 new(value: T) -> Self31 fn new(value: T) -> Self { 32 Self(spin::Mutex::new(value)) 33 } 34 } 35 36 /// A reader-writer lock 37 /// This type of lock allows a number of readers or at most one writer at any point in time. 38 /// The write portion of this lock typically allows modification of the underlying data (exclusive access) 39 /// and the read portion of this lock typically allows for read-only access (shared access). 40 pub struct RwLock<T>(spin::RwLock<T>); 41 42 impl<T> RwLock<T> { 43 /// Creates a new instance of an `RwLock<T>` which is unlocked. new(inner: T) -> Self44 pub const fn new(inner: T) -> Self { 45 Self(spin::RwLock::new(inner)) 46 } 47 } 48 49 impl<T> crate::RwLock<T> for RwLock<T> { 50 type RwLockReadGuard<'a> = spin::RwLockReadGuard<'a, T> where T: 'a; 51 type RwLockWriteGuard<'a> = spin::RwLockWriteGuard<'a, T> where T: 'a; 52 read(&self) -> Self::RwLockReadGuard<'_>53 fn read(&self) -> Self::RwLockReadGuard<'_> { 54 self.0.read() 55 } 56 write(&self) -> Self::RwLockWriteGuard<'_>57 fn write(&self) -> Self::RwLockWriteGuard<'_> { 58 self.0.write() 59 } 60 } 61