1 // Copyright 2018 Amanieu d'Antras
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
8 use core
::cell
::UnsafeCell
;
10 use core
::marker
::PhantomData
;
12 use core
::ops
::{Deref, DerefMut}
;
14 #[cfg(feature = "arc_lock")]
16 #[cfg(feature = "arc_lock")]
17 use core
::mem
::ManuallyDrop
;
18 #[cfg(feature = "arc_lock")]
21 #[cfg(feature = "owning_ref")]
22 use owning_ref
::StableAddress
;
24 #[cfg(feature = "serde")]
25 use serde
::{Deserialize, Deserializer, Serialize, Serializer}
;
27 /// Basic operations for a mutex.
29 /// Types implementing this trait can be used by `Mutex` to form a safe and
30 /// fully-functioning mutex type.
34 /// Implementations of this trait must ensure that the mutex is actually
35 /// exclusive: a lock can't be acquired while the mutex is already locked.
36 pub unsafe trait RawMutex
{
37 /// Initial value for an unlocked mutex.
38 // A “non-constant” const item is a legacy way to supply an initialized value to downstream
39 // static items. Can hopefully be replaced with `const fn new() -> Self` at some point.
40 #[allow(clippy::declare_interior_mutable_const)]
43 /// Marker type which determines whether a lock guard should be `Send`. Use
44 /// one of the `GuardSend` or `GuardNoSend` helper types here.
47 /// Acquires this mutex, blocking the current thread until it is able to do so.
50 /// Attempts to acquire this mutex without blocking. Returns `true`
51 /// if the lock was successfully acquired and `false` otherwise.
52 fn try_lock(&self) -> bool
;
54 /// Unlocks this mutex.
58 /// This method may only be called if the mutex is held in the current context, i.e. it must
59 /// be paired with a successful call to [`lock`], [`try_lock`], [`try_lock_for`] or [`try_lock_until`].
61 /// [`lock`]: #tymethod.lock
62 /// [`try_lock`]: #tymethod.try_lock
63 /// [`try_lock_for`]: trait.RawMutexTimed.html#tymethod.try_lock_for
64 /// [`try_lock_until`]: trait.RawMutexTimed.html#tymethod.try_lock_until
65 unsafe fn unlock(&self);
67 /// Checks whether the mutex is currently locked.
69 fn is_locked(&self) -> bool
{
70 let acquired_lock
= self.try_lock();
72 // Safety: The lock has been successfully acquired above.
81 /// Additional methods for mutexes which support fair unlocking.
83 /// Fair unlocking means that a lock is handed directly over to the next waiting
84 /// thread if there is one, without giving other threads the opportunity to
85 /// "steal" the lock in the meantime. This is typically slower than unfair
86 /// unlocking, but may be necessary in certain circumstances.
87 pub unsafe trait RawMutexFair
: RawMutex
{
88 /// Unlocks this mutex using a fair unlock protocol.
92 /// This method may only be called if the mutex is held in the current context, see
93 /// the documentation of [`unlock`].
95 /// [`unlock`]: trait.RawMutex.html#tymethod.unlock
96 unsafe fn unlock_fair(&self);
98 /// Temporarily yields the mutex to a waiting thread if there is one.
100 /// This method is functionally equivalent to calling `unlock_fair` followed
101 /// by `lock`, however it can be much more efficient in the case where there
102 /// are no waiting threads.
106 /// This method may only be called if the mutex is held in the current context, see
107 /// the documentation of [`unlock`].
109 /// [`unlock`]: trait.RawMutex.html#tymethod.unlock
110 unsafe fn bump(&self) {
116 /// Additional methods for mutexes which support locking with timeouts.
118 /// The `Duration` and `Instant` types are specified as associated types so that
119 /// this trait is usable even in `no_std` environments.
120 pub unsafe trait RawMutexTimed
: RawMutex
{
121 /// Duration type used for `try_lock_for`.
124 /// Instant type used for `try_lock_until`.
127 /// Attempts to acquire this lock until a timeout is reached.
128 fn try_lock_for(&self, timeout
: Self::Duration
) -> bool
;
130 /// Attempts to acquire this lock until a timeout is reached.
131 fn try_lock_until(&self, timeout
: Self::Instant
) -> bool
;
134 /// A mutual exclusion primitive useful for protecting shared data
136 /// This mutex will block threads waiting for the lock to become available. The
137 /// mutex can also be statically initialized or created via a `new`
138 /// constructor. Each mutex has a type parameter which represents the data that
139 /// it is protecting. The data can only be accessed through the RAII guards
140 /// returned from `lock` and `try_lock`, which guarantees that the data is only
141 /// ever accessed when the mutex is locked.
142 pub struct Mutex
<R
, T
: ?Sized
> {
147 unsafe impl<R
: RawMutex
+ Send
, T
: ?Sized
+ Send
> Send
for Mutex
<R
, T
> {}
148 unsafe impl<R
: RawMutex
+ Sync
, T
: ?Sized
+ Send
> Sync
for Mutex
<R
, T
> {}
150 impl<R
: RawMutex
, T
> Mutex
<R
, T
> {
151 /// Creates a new mutex in an unlocked state ready for use.
152 #[cfg(has_const_fn_trait_bound)]
154 pub const fn new(val
: T
) -> Mutex
<R
, T
> {
157 data
: UnsafeCell
::new(val
),
161 /// Creates a new mutex in an unlocked state ready for use.
162 #[cfg(not(has_const_fn_trait_bound))]
164 pub fn new(val
: T
) -> Mutex
<R
, T
> {
167 data
: UnsafeCell
::new(val
),
171 /// Consumes this mutex, returning the underlying data.
173 pub fn into_inner(self) -> T
{
174 self.data
.into_inner()
178 impl<R
, T
> Mutex
<R
, T
> {
179 /// Creates a new mutex based on a pre-existing raw mutex.
181 /// This allows creating a mutex in a constant context on stable Rust.
183 pub const fn const_new(raw_mutex
: R
, val
: T
) -> Mutex
<R
, T
> {
186 data
: UnsafeCell
::new(val
),
191 impl<R
: RawMutex
, T
: ?Sized
> Mutex
<R
, T
> {
194 /// The lock must be held when calling this method.
196 unsafe fn guard(&self) -> MutexGuard
<'_
, R
, T
> {
203 /// Acquires a mutex, blocking the current thread until it is able to do so.
205 /// This function will block the local thread until it is available to acquire
206 /// the mutex. Upon returning, the thread is the only thread with the mutex
207 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
208 /// the guard goes out of scope, the mutex will be unlocked.
210 /// Attempts to lock a mutex in the thread which already holds the lock will
211 /// result in a deadlock.
213 pub fn lock(&self) -> MutexGuard
<'_
, R
, T
> {
215 // SAFETY: The lock is held, as required.
216 unsafe { self.guard() }
219 /// Attempts to acquire this lock.
221 /// If the lock could not be acquired at this time, then `None` is returned.
222 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
223 /// guard is dropped.
225 /// This function does not block.
227 pub fn try_lock(&self) -> Option
<MutexGuard
<'_
, R
, T
>> {
228 if self.raw
.try_lock() {
229 // SAFETY: The lock is held, as required.
230 Some(unsafe { self.guard() }
)
236 /// Returns a mutable reference to the underlying data.
238 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
239 /// take place---the mutable borrow statically guarantees no locks exist.
241 pub fn get_mut(&mut self) -> &mut T
{
242 unsafe { &mut *self.data.get() }
245 /// Checks whether the mutex is currently locked.
247 pub fn is_locked(&self) -> bool
{
251 /// Forcibly unlocks the mutex.
253 /// This is useful when combined with `mem::forget` to hold a lock without
254 /// the need to maintain a `MutexGuard` object alive, for example when
255 /// dealing with FFI.
259 /// This method must only be called if the current thread logically owns a
260 /// `MutexGuard` but that guard has be discarded using `mem::forget`.
261 /// Behavior is undefined if a mutex is unlocked when not locked.
263 pub unsafe fn force_unlock(&self) {
267 /// Returns the underlying raw mutex object.
269 /// Note that you will most likely need to import the `RawMutex` trait from
270 /// `lock_api` to be able to call functions on the raw mutex.
274 /// This method is unsafe because it allows unlocking a mutex while
275 /// still holding a reference to a `MutexGuard`.
277 pub unsafe fn raw(&self) -> &R
{
281 /// Returns a raw pointer to the underlying data.
283 /// This is useful when combined with `mem::forget` to hold a lock without
284 /// the need to maintain a `MutexGuard` object alive, for example when
285 /// dealing with FFI.
289 /// You must ensure that there are no data races when dereferencing the
290 /// returned pointer, for example if the current thread logically owns
291 /// a `MutexGuard` but that guard has been discarded using `mem::forget`.
293 pub fn data_ptr(&self) -> *mut T
{
299 /// The lock needs to be held for the behavior of this function to be defined.
300 #[cfg(feature = "arc_lock")]
302 unsafe fn guard_arc(self: &Arc
<Self>) -> ArcMutexGuard
<R
, T
> {
309 /// Acquires a lock through an `Arc`.
311 /// This method is similar to the `lock` method; however, it requires the `Mutex` to be inside of an `Arc`
312 /// and the resulting mutex guard has no lifetime requirements.
313 #[cfg(feature = "arc_lock")]
315 pub fn lock_arc(self: &Arc
<Self>) -> ArcMutexGuard
<R
, T
> {
317 // SAFETY: the locking guarantee is upheld
318 unsafe { self.guard_arc() }
321 /// Attempts to acquire a lock through an `Arc`.
323 /// This method is similar to the `try_lock` method; however, it requires the `Mutex` to be inside of an
324 /// `Arc` and the resulting mutex guard has no lifetime requirements.
325 #[cfg(feature = "arc_lock")]
327 pub fn try_lock_arc(self: &Arc
<Self>) -> Option
<ArcMutexGuard
<R
, T
>> {
328 if self.raw
.try_lock() {
329 // SAFETY: locking guarantee is upheld
330 Some(unsafe { self.guard_arc() }
)
337 impl<R
: RawMutexFair
, T
: ?Sized
> Mutex
<R
, T
> {
338 /// Forcibly unlocks the mutex using a fair unlock procotol.
340 /// This is useful when combined with `mem::forget` to hold a lock without
341 /// the need to maintain a `MutexGuard` object alive, for example when
342 /// dealing with FFI.
346 /// This method must only be called if the current thread logically owns a
347 /// `MutexGuard` but that guard has be discarded using `mem::forget`.
348 /// Behavior is undefined if a mutex is unlocked when not locked.
350 pub unsafe fn force_unlock_fair(&self) {
351 self.raw
.unlock_fair();
355 impl<R
: RawMutexTimed
, T
: ?Sized
> Mutex
<R
, T
> {
356 /// Attempts to acquire this lock until a timeout is reached.
358 /// If the lock could not be acquired before the timeout expired, then
359 /// `None` is returned. Otherwise, an RAII guard is returned. The lock will
360 /// be unlocked when the guard is dropped.
362 pub fn try_lock_for(&self, timeout
: R
::Duration
) -> Option
<MutexGuard
<'_
, R
, T
>> {
363 if self.raw
.try_lock_for(timeout
) {
364 // SAFETY: The lock is held, as required.
365 Some(unsafe { self.guard() }
)
371 /// Attempts to acquire this lock until a timeout is reached.
373 /// If the lock could not be acquired before the timeout expired, then
374 /// `None` is returned. Otherwise, an RAII guard is returned. The lock will
375 /// be unlocked when the guard is dropped.
377 pub fn try_lock_until(&self, timeout
: R
::Instant
) -> Option
<MutexGuard
<'_
, R
, T
>> {
378 if self.raw
.try_lock_until(timeout
) {
379 // SAFETY: The lock is held, as required.
380 Some(unsafe { self.guard() }
)
386 /// Attempts to acquire this lock through an `Arc` until a timeout is reached.
388 /// This method is similar to the `try_lock_for` method; however, it requires the `Mutex` to be inside of an
389 /// `Arc` and the resulting mutex guard has no lifetime requirements.
390 #[cfg(feature = "arc_lock")]
392 pub fn try_lock_arc_for(self: &Arc
<Self>, timeout
: R
::Duration
) -> Option
<ArcMutexGuard
<R
, T
>> {
393 if self.raw
.try_lock_for(timeout
) {
394 // SAFETY: locking guarantee is upheld
395 Some(unsafe { self.guard_arc() }
)
401 /// Attempts to acquire this lock through an `Arc` until a timeout is reached.
403 /// This method is similar to the `try_lock_until` method; however, it requires the `Mutex` to be inside of
404 /// an `Arc` and the resulting mutex guard has no lifetime requirements.
405 #[cfg(feature = "arc_lock")]
407 pub fn try_lock_arc_until(
410 ) -> Option
<ArcMutexGuard
<R
, T
>> {
411 if self.raw
.try_lock_until(timeout
) {
412 // SAFETY: locking guarantee is upheld
413 Some(unsafe { self.guard_arc() }
)
420 impl<R
: RawMutex
, T
: ?Sized
+ Default
> Default
for Mutex
<R
, T
> {
422 fn default() -> Mutex
<R
, T
> {
423 Mutex
::new(Default
::default())
427 impl<R
: RawMutex
, T
> From
<T
> for Mutex
<R
, T
> {
429 fn from(t
: T
) -> Mutex
<R
, T
> {
434 impl<R
: RawMutex
, T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Mutex
<R
, T
> {
435 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
436 match self.try_lock() {
437 Some(guard
) => f
.debug_struct("Mutex").field("data", &&*guard
).finish(),
439 struct LockedPlaceholder
;
440 impl fmt
::Debug
for LockedPlaceholder
{
441 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
442 f
.write_str("<locked>")
446 f
.debug_struct("Mutex")
447 .field("data", &LockedPlaceholder
)
454 // Copied and modified from serde
455 #[cfg(feature = "serde")]
456 impl<R
, T
> Serialize
for Mutex
<R
, T
>
459 T
: Serialize
+ ?Sized
,
461 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
465 self.lock().serialize(serializer
)
469 #[cfg(feature = "serde")]
470 impl<'de
, R
, T
> Deserialize
<'de
> for Mutex
<R
, T
>
473 T
: Deserialize
<'de
> + ?Sized
,
475 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
477 D
: Deserializer
<'de
>,
479 Deserialize
::deserialize(deserializer
).map(Mutex
::new
)
483 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
484 /// dropped (falls out of scope), the lock will be unlocked.
486 /// The data protected by the mutex can be accessed through this guard via its
487 /// `Deref` and `DerefMut` implementations.
488 #[must_use = "if unused the Mutex will immediately unlock"]
489 pub struct MutexGuard
<'a
, R
: RawMutex
, T
: ?Sized
> {
490 mutex
: &'a Mutex
<R
, T
>,
491 marker
: PhantomData
<(&'a
mut T
, R
::GuardMarker
)>,
494 unsafe impl<'a
, R
: RawMutex
+ Sync
+ 'a
, T
: ?Sized
+ Sync
+ 'a
> Sync
for MutexGuard
<'a
, R
, T
> {}
496 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> MutexGuard
<'a
, R
, T
> {
497 /// Returns a reference to the original `Mutex` object.
498 pub fn mutex(s
: &Self) -> &'a Mutex
<R
, T
> {
502 /// Makes a new `MappedMutexGuard` for a component of the locked data.
504 /// This operation cannot fail as the `MutexGuard` passed
505 /// in already locked the mutex.
507 /// This is an associated function that needs to be
508 /// used as `MutexGuard::map(...)`. A method would interfere with methods of
509 /// the same name on the contents of the locked data.
511 pub fn map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> MappedMutexGuard
<'a
, R
, U
>
513 F
: FnOnce(&mut T
) -> &mut U
,
515 let raw
= &s
.mutex
.raw
;
516 let data
= f(unsafe { &mut *s.mutex.data.get() }
);
525 /// Attempts to make a new `MappedMutexGuard` for a component of the
526 /// locked data. The original guard is returned if the closure returns `None`.
528 /// This operation cannot fail as the `MutexGuard` passed
529 /// in already locked the mutex.
531 /// This is an associated function that needs to be
532 /// used as `MutexGuard::try_map(...)`. A method would interfere with methods of
533 /// the same name on the contents of the locked data.
535 pub fn try_map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> Result
<MappedMutexGuard
<'a
, R
, U
>, Self>
537 F
: FnOnce(&mut T
) -> Option
<&mut U
>,
539 let raw
= &s
.mutex
.raw
;
540 let data
= match f(unsafe { &mut *s.mutex.data.get() }
) {
542 None
=> return Err(s
),
545 Ok(MappedMutexGuard
{
552 /// Temporarily unlocks the mutex to execute the given function.
554 /// This is safe because `&mut` guarantees that there exist no other
555 /// references to the data protected by the mutex.
557 pub fn unlocked
<F
, U
>(s
: &mut Self, f
: F
) -> U
561 // Safety: A MutexGuard always holds the lock.
563 s
.mutex
.raw
.unlock();
565 defer
!(s
.mutex
.raw
.lock());
569 /// Leaks the mutex guard and returns a mutable reference to the data
570 /// protected by the mutex.
572 /// This will leave the `Mutex` in a locked state.
574 pub fn leak(s
: Self) -> &'a
mut T
{
575 let r
= unsafe { &mut *s.mutex.data.get() }
;
581 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MutexGuard
<'a
, R
, T
> {
582 /// Unlocks the mutex using a fair unlock protocol.
584 /// By default, mutexes are unfair and allow the current thread to re-lock
585 /// the mutex before another has the chance to acquire the lock, even if
586 /// that thread has been blocked on the mutex for a long time. This is the
587 /// default because it allows much higher throughput as it avoids forcing a
588 /// context switch on every mutex unlock. This can result in one thread
589 /// acquiring a mutex many more times than other threads.
591 /// However in some cases it can be beneficial to ensure fairness by forcing
592 /// the lock to pass on to a waiting thread if there is one. This is done by
593 /// using this method instead of dropping the `MutexGuard` normally.
595 pub fn unlock_fair(s
: Self) {
596 // Safety: A MutexGuard always holds the lock.
598 s
.mutex
.raw
.unlock_fair();
603 /// Temporarily unlocks the mutex to execute the given function.
605 /// The mutex is unlocked using a fair unlock protocol.
607 /// This is safe because `&mut` guarantees that there exist no other
608 /// references to the data protected by the mutex.
610 pub fn unlocked_fair
<F
, U
>(s
: &mut Self, f
: F
) -> U
614 // Safety: A MutexGuard always holds the lock.
616 s
.mutex
.raw
.unlock_fair();
618 defer
!(s
.mutex
.raw
.lock());
622 /// Temporarily yields the mutex to a waiting thread if there is one.
624 /// This method is functionally equivalent to calling `unlock_fair` followed
625 /// by `lock`, however it can be much more efficient in the case where there
626 /// are no waiting threads.
628 pub fn bump(s
: &mut Self) {
629 // Safety: A MutexGuard always holds the lock.
636 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MutexGuard
<'a
, R
, T
> {
639 fn deref(&self) -> &T
{
640 unsafe { &*self.mutex.data.get() }
644 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MutexGuard
<'a
, R
, T
> {
646 fn deref_mut(&mut self) -> &mut T
{
647 unsafe { &mut *self.mutex.data.get() }
651 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MutexGuard
<'a
, R
, T
> {
654 // Safety: A MutexGuard always holds the lock.
656 self.mutex
.raw
.unlock();
661 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MutexGuard
<'a
, R
, T
> {
662 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
663 fmt
::Debug
::fmt(&**self, f
)
667 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
for MutexGuard
<'a
, R
, T
> {
668 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
673 #[cfg(feature = "owning_ref")]
674 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MutexGuard
<'a
, R
, T
> {}
676 /// An RAII mutex guard returned by the `Arc` locking operations on `Mutex`.
678 /// This is similar to the `MutexGuard` struct, except instead of using a reference to unlock the `Mutex` it
679 /// uses an `Arc<Mutex>`. This has several advantages, most notably that it has an `'static` lifetime.
680 #[cfg(feature = "arc_lock")]
681 #[must_use = "if unused the Mutex will immediately unlock"]
682 pub struct ArcMutexGuard
<R
: RawMutex
, T
: ?Sized
> {
683 mutex
: Arc
<Mutex
<R
, T
>>,
684 marker
: PhantomData
<*const ()>,
687 #[cfg(feature = "arc_lock")]
688 unsafe impl<R
: RawMutex
+ Send
+ Sync
, T
: Send
+ ?Sized
> Send
for ArcMutexGuard
<R
, T
> where
692 #[cfg(feature = "arc_lock")]
693 unsafe impl<R
: RawMutex
+ Sync
, T
: Sync
+ ?Sized
> Sync
for ArcMutexGuard
<R
, T
> where
698 #[cfg(feature = "arc_lock")]
699 impl<R
: RawMutex
, T
: ?Sized
> ArcMutexGuard
<R
, T
> {
700 /// Returns a reference to the `Mutex` this is guarding, contained in its `Arc`.
702 pub fn mutex(s
: &Self) -> &Arc
<Mutex
<R
, T
>> {
706 /// Unlocks the mutex and returns the `Arc` that was held by the [`ArcMutexGuard`].
708 pub fn into_arc(s
: Self) -> Arc
<Mutex
<R
, T
>> {
709 // Safety: Skip our Drop impl and manually unlock the mutex.
710 let arc
= unsafe { ptr::read(&s.mutex) }
;
718 /// Temporarily unlocks the mutex to execute the given function.
720 /// This is safe because `&mut` guarantees that there exist no other
721 /// references to the data protected by the mutex.
723 pub fn unlocked
<F
, U
>(s
: &mut Self, f
: F
) -> U
727 // Safety: A MutexGuard always holds the lock.
729 s
.mutex
.raw
.unlock();
731 defer
!(s
.mutex
.raw
.lock());
736 #[cfg(feature = "arc_lock")]
737 impl<R
: RawMutexFair
, T
: ?Sized
> ArcMutexGuard
<R
, T
> {
738 /// Unlocks the mutex using a fair unlock protocol.
740 /// This is functionally identical to the `unlock_fair` method on [`MutexGuard`].
742 pub fn unlock_fair(s
: Self) {
743 // Safety: A MutexGuard always holds the lock.
745 s
.mutex
.raw
.unlock_fair();
748 // SAFETY: make sure the Arc gets it reference decremented
749 let mut s
= ManuallyDrop
::new(s
);
750 unsafe { ptr::drop_in_place(&mut s.mutex) }
;
753 /// Temporarily unlocks the mutex to execute the given function.
755 /// This is functionally identical to the `unlocked_fair` method on [`MutexGuard`].
757 pub fn unlocked_fair
<F
, U
>(s
: &mut Self, f
: F
) -> U
761 // Safety: A MutexGuard always holds the lock.
763 s
.mutex
.raw
.unlock_fair();
765 defer
!(s
.mutex
.raw
.lock());
769 /// Temporarily yields the mutex to a waiting thread if there is one.
771 /// This is functionally identical to the `bump` method on [`MutexGuard`].
773 pub fn bump(s
: &mut Self) {
774 // Safety: A MutexGuard always holds the lock.
781 #[cfg(feature = "arc_lock")]
782 impl<R
: RawMutex
, T
: ?Sized
> Deref
for ArcMutexGuard
<R
, T
> {
785 fn deref(&self) -> &T
{
786 unsafe { &*self.mutex.data.get() }
790 #[cfg(feature = "arc_lock")]
791 impl<R
: RawMutex
, T
: ?Sized
> DerefMut
for ArcMutexGuard
<R
, T
> {
793 fn deref_mut(&mut self) -> &mut T
{
794 unsafe { &mut *self.mutex.data.get() }
798 #[cfg(feature = "arc_lock")]
799 impl<R
: RawMutex
, T
: ?Sized
> Drop
for ArcMutexGuard
<R
, T
> {
802 // Safety: A MutexGuard always holds the lock.
804 self.mutex
.raw
.unlock();
809 /// An RAII mutex guard returned by `MutexGuard::map`, which can point to a
810 /// subfield of the protected data.
812 /// The main difference between `MappedMutexGuard` and `MutexGuard` is that the
813 /// former doesn't support temporarily unlocking and re-locking, since that
814 /// could introduce soundness issues if the locked object is modified by another
816 #[must_use = "if unused the Mutex will immediately unlock"]
817 pub struct MappedMutexGuard
<'a
, R
: RawMutex
, T
: ?Sized
> {
820 marker
: PhantomData
<&'a
mut T
>,
823 unsafe impl<'a
, R
: RawMutex
+ Sync
+ 'a
, T
: ?Sized
+ Sync
+ 'a
> Sync
824 for MappedMutexGuard
<'a
, R
, T
>
827 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ Send
+ 'a
> Send
for MappedMutexGuard
<'a
, R
, T
> where
832 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
833 /// Makes a new `MappedMutexGuard` for a component of the locked data.
835 /// This operation cannot fail as the `MappedMutexGuard` passed
836 /// in already locked the mutex.
838 /// This is an associated function that needs to be
839 /// used as `MappedMutexGuard::map(...)`. A method would interfere with methods of
840 /// the same name on the contents of the locked data.
842 pub fn map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> MappedMutexGuard
<'a
, R
, U
>
844 F
: FnOnce(&mut T
) -> &mut U
,
847 let data
= f(unsafe { &mut *s.data }
);
856 /// Attempts to make a new `MappedMutexGuard` for a component of the
857 /// locked data. The original guard is returned if the closure returns `None`.
859 /// This operation cannot fail as the `MappedMutexGuard` passed
860 /// in already locked the mutex.
862 /// This is an associated function that needs to be
863 /// used as `MappedMutexGuard::try_map(...)`. A method would interfere with methods of
864 /// the same name on the contents of the locked data.
866 pub fn try_map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> Result
<MappedMutexGuard
<'a
, R
, U
>, Self>
868 F
: FnOnce(&mut T
) -> Option
<&mut U
>,
871 let data
= match f(unsafe { &mut *s.data }
) {
873 None
=> return Err(s
),
876 Ok(MappedMutexGuard
{
884 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
885 /// Unlocks the mutex using a fair unlock protocol.
887 /// By default, mutexes are unfair and allow the current thread to re-lock
888 /// the mutex before another has the chance to acquire the lock, even if
889 /// that thread has been blocked on the mutex for a long time. This is the
890 /// default because it allows much higher throughput as it avoids forcing a
891 /// context switch on every mutex unlock. This can result in one thread
892 /// acquiring a mutex many more times than other threads.
894 /// However in some cases it can be beneficial to ensure fairness by forcing
895 /// the lock to pass on to a waiting thread if there is one. This is done by
896 /// using this method instead of dropping the `MutexGuard` normally.
898 pub fn unlock_fair(s
: Self) {
899 // Safety: A MutexGuard always holds the lock.
907 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MappedMutexGuard
<'a
, R
, T
> {
910 fn deref(&self) -> &T
{
911 unsafe { &*self.data }
915 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MappedMutexGuard
<'a
, R
, T
> {
917 fn deref_mut(&mut self) -> &mut T
{
918 unsafe { &mut *self.data }
922 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MappedMutexGuard
<'a
, R
, T
> {
925 // Safety: A MappedMutexGuard always holds the lock.
932 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MappedMutexGuard
<'a
, R
, T
> {
933 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
934 fmt
::Debug
::fmt(&**self, f
)
938 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
939 for MappedMutexGuard
<'a
, R
, T
>
941 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
946 #[cfg(feature = "owning_ref")]
947 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MappedMutexGuard
<'a
, R
, T
> {}