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(feature = "nightly")]
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(feature = "nightly"))]
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());
570 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MutexGuard
<'a
, R
, T
> {
571 /// Unlocks the mutex using a fair unlock protocol.
573 /// By default, mutexes are unfair and allow the current thread to re-lock
574 /// the mutex before another has the chance to acquire the lock, even if
575 /// that thread has been blocked on the mutex for a long time. This is the
576 /// default because it allows much higher throughput as it avoids forcing a
577 /// context switch on every mutex unlock. This can result in one thread
578 /// acquiring a mutex many more times than other threads.
580 /// However in some cases it can be beneficial to ensure fairness by forcing
581 /// the lock to pass on to a waiting thread if there is one. This is done by
582 /// using this method instead of dropping the `MutexGuard` normally.
584 pub fn unlock_fair(s
: Self) {
585 // Safety: A MutexGuard always holds the lock.
587 s
.mutex
.raw
.unlock_fair();
592 /// Temporarily unlocks the mutex to execute the given function.
594 /// The mutex is unlocked using a fair unlock protocol.
596 /// This is safe because `&mut` guarantees that there exist no other
597 /// references to the data protected by the mutex.
599 pub fn unlocked_fair
<F
, U
>(s
: &mut Self, f
: F
) -> U
603 // Safety: A MutexGuard always holds the lock.
605 s
.mutex
.raw
.unlock_fair();
607 defer
!(s
.mutex
.raw
.lock());
611 /// Temporarily yields the mutex to a waiting thread if there is one.
613 /// This method is functionally equivalent to calling `unlock_fair` followed
614 /// by `lock`, however it can be much more efficient in the case where there
615 /// are no waiting threads.
617 pub fn bump(s
: &mut Self) {
618 // Safety: A MutexGuard always holds the lock.
625 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MutexGuard
<'a
, R
, T
> {
628 fn deref(&self) -> &T
{
629 unsafe { &*self.mutex.data.get() }
633 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MutexGuard
<'a
, R
, T
> {
635 fn deref_mut(&mut self) -> &mut T
{
636 unsafe { &mut *self.mutex.data.get() }
640 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MutexGuard
<'a
, R
, T
> {
643 // Safety: A MutexGuard always holds the lock.
645 self.mutex
.raw
.unlock();
650 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MutexGuard
<'a
, R
, T
> {
651 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
652 fmt
::Debug
::fmt(&**self, f
)
656 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
for MutexGuard
<'a
, R
, T
> {
657 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
662 #[cfg(feature = "owning_ref")]
663 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MutexGuard
<'a
, R
, T
> {}
665 /// An RAII mutex guard returned by the `Arc` locking operations on `Mutex`.
667 /// This is similar to the `MutexGuard` struct, except instead of using a reference to unlock the `Mutex` it
668 /// uses an `Arc<Mutex>`. This has several advantages, most notably that it has an `'static` lifetime.
669 #[cfg(feature = "arc_lock")]
670 #[must_use = "if unused the Mutex will immediately unlock"]
671 pub struct ArcMutexGuard
<R
: RawMutex
, T
: ?Sized
> {
672 mutex
: Arc
<Mutex
<R
, T
>>,
673 marker
: PhantomData
<R
::GuardMarker
>,
676 #[cfg(feature = "arc_lock")]
677 impl<R
: RawMutex
, T
: ?Sized
> ArcMutexGuard
<R
, T
> {
678 /// Returns a reference to the `Mutex` this is guarding, contained in its `Arc`.
680 pub fn mutex(&self) -> &Arc
<Mutex
<R
, T
>> {
684 /// Temporarily unlocks the mutex to execute the given function.
686 /// This is safe because `&mut` guarantees that there exist no other
687 /// references to the data protected by the mutex.
689 pub fn unlocked
<F
, U
>(s
: &mut Self, f
: F
) -> U
693 // Safety: A MutexGuard always holds the lock.
695 s
.mutex
.raw
.unlock();
697 defer
!(s
.mutex
.raw
.lock());
702 #[cfg(feature = "arc_lock")]
703 impl<R
: RawMutexFair
, T
: ?Sized
> ArcMutexGuard
<R
, T
> {
704 /// Unlocks the mutex using a fair unlock protocol.
706 /// This is functionally identical to the `unlock_fair` method on [`MutexGuard`].
708 pub fn unlock_fair(s
: Self) {
709 // Safety: A MutexGuard always holds the lock.
711 s
.mutex
.raw
.unlock_fair();
714 // SAFETY: make sure the Arc gets it reference decremented
715 let mut s
= ManuallyDrop
::new(s
);
716 unsafe { ptr::drop_in_place(&mut s.mutex) }
;
719 /// Temporarily unlocks the mutex to execute the given function.
721 /// This is functionally identical to the `unlocked_fair` method on [`MutexGuard`].
723 pub fn unlocked_fair
<F
, U
>(s
: &mut Self, f
: F
) -> U
727 // Safety: A MutexGuard always holds the lock.
729 s
.mutex
.raw
.unlock_fair();
731 defer
!(s
.mutex
.raw
.lock());
735 /// Temporarily yields the mutex to a waiting thread if there is one.
737 /// This is functionally identical to the `bump` method on [`MutexGuard`].
739 pub fn bump(s
: &mut Self) {
740 // Safety: A MutexGuard always holds the lock.
747 #[cfg(feature = "arc_lock")]
748 impl<R
: RawMutex
, T
: ?Sized
> Deref
for ArcMutexGuard
<R
, T
> {
751 fn deref(&self) -> &T
{
752 unsafe { &*self.mutex.data.get() }
756 #[cfg(feature = "arc_lock")]
757 impl<R
: RawMutex
, T
: ?Sized
> DerefMut
for ArcMutexGuard
<R
, T
> {
759 fn deref_mut(&mut self) -> &mut T
{
760 unsafe { &mut *self.mutex.data.get() }
764 #[cfg(feature = "arc_lock")]
765 impl<R
: RawMutex
, T
: ?Sized
> Drop
for ArcMutexGuard
<R
, T
> {
768 // Safety: A MutexGuard always holds the lock.
770 self.mutex
.raw
.unlock();
775 /// An RAII mutex guard returned by `MutexGuard::map`, which can point to a
776 /// subfield of the protected data.
778 /// The main difference between `MappedMutexGuard` and `MutexGuard` is that the
779 /// former doesn't support temporarily unlocking and re-locking, since that
780 /// could introduce soundness issues if the locked object is modified by another
782 #[must_use = "if unused the Mutex will immediately unlock"]
783 pub struct MappedMutexGuard
<'a
, R
: RawMutex
, T
: ?Sized
> {
786 marker
: PhantomData
<&'a
mut T
>,
789 unsafe impl<'a
, R
: RawMutex
+ Sync
+ 'a
, T
: ?Sized
+ Sync
+ 'a
> Sync
790 for MappedMutexGuard
<'a
, R
, T
>
793 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ Send
+ 'a
> Send
for MappedMutexGuard
<'a
, R
, T
> where
798 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
799 /// Makes a new `MappedMutexGuard` for a component of the locked data.
801 /// This operation cannot fail as the `MappedMutexGuard` passed
802 /// in already locked the mutex.
804 /// This is an associated function that needs to be
805 /// used as `MappedMutexGuard::map(...)`. A method would interfere with methods of
806 /// the same name on the contents of the locked data.
808 pub fn map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> MappedMutexGuard
<'a
, R
, U
>
810 F
: FnOnce(&mut T
) -> &mut U
,
813 let data
= f(unsafe { &mut *s.data }
);
822 /// Attempts to make a new `MappedMutexGuard` for a component of the
823 /// locked data. The original guard is returned if the closure returns `None`.
825 /// This operation cannot fail as the `MappedMutexGuard` passed
826 /// in already locked the mutex.
828 /// This is an associated function that needs to be
829 /// used as `MappedMutexGuard::try_map(...)`. A method would interfere with methods of
830 /// the same name on the contents of the locked data.
832 pub fn try_map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> Result
<MappedMutexGuard
<'a
, R
, U
>, Self>
834 F
: FnOnce(&mut T
) -> Option
<&mut U
>,
837 let data
= match f(unsafe { &mut *s.data }
) {
839 None
=> return Err(s
),
842 Ok(MappedMutexGuard
{
850 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
851 /// Unlocks the mutex using a fair unlock protocol.
853 /// By default, mutexes are unfair and allow the current thread to re-lock
854 /// the mutex before another has the chance to acquire the lock, even if
855 /// that thread has been blocked on the mutex for a long time. This is the
856 /// default because it allows much higher throughput as it avoids forcing a
857 /// context switch on every mutex unlock. This can result in one thread
858 /// acquiring a mutex many more times than other threads.
860 /// However in some cases it can be beneficial to ensure fairness by forcing
861 /// the lock to pass on to a waiting thread if there is one. This is done by
862 /// using this method instead of dropping the `MutexGuard` normally.
864 pub fn unlock_fair(s
: Self) {
865 // Safety: A MutexGuard always holds the lock.
873 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MappedMutexGuard
<'a
, R
, T
> {
876 fn deref(&self) -> &T
{
877 unsafe { &*self.data }
881 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MappedMutexGuard
<'a
, R
, T
> {
883 fn deref_mut(&mut self) -> &mut T
{
884 unsafe { &mut *self.data }
888 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MappedMutexGuard
<'a
, R
, T
> {
891 // Safety: A MappedMutexGuard always holds the lock.
898 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MappedMutexGuard
<'a
, R
, T
> {
899 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
900 fmt
::Debug
::fmt(&**self, f
)
904 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
905 for MappedMutexGuard
<'a
, R
, T
>
907 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
912 #[cfg(feature = "owning_ref")]
913 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MappedMutexGuard
<'a
, R
, T
> {}