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 = "owning_ref")]
15 use owning_ref
::StableAddress
;
17 #[cfg(feature = "serde")]
18 use serde
::{Deserialize, Deserializer, Serialize, Serializer}
;
20 /// Basic operations for a mutex.
22 /// Types implementing this trait can be used by `Mutex` to form a safe and
23 /// fully-functioning mutex type.
27 /// Implementations of this trait must ensure that the mutex is actually
28 /// exclusive: a lock can't be acquired while the mutex is already locked.
29 pub unsafe trait RawMutex
{
30 /// Initial value for an unlocked mutex.
31 // A “non-constant” const item is a legacy way to supply an initialized value to downstream
32 // static items. Can hopefully be replaced with `const fn new() -> Self` at some point.
33 #[allow(clippy::declare_interior_mutable_const)]
36 /// Marker type which determines whether a lock guard should be `Send`. Use
37 /// one of the `GuardSend` or `GuardNoSend` helper types here.
40 /// Acquires this mutex, blocking the current thread until it is able to do so.
43 /// Attempts to acquire this mutex without blocking. Returns `true`
44 /// if the lock was successfully acquired and `false` otherwise.
45 fn try_lock(&self) -> bool
;
47 /// Unlocks this mutex.
51 /// Additional methods for mutexes which support fair unlocking.
53 /// Fair unlocking means that a lock is handed directly over to the next waiting
54 /// thread if there is one, without giving other threads the opportunity to
55 /// "steal" the lock in the meantime. This is typically slower than unfair
56 /// unlocking, but may be necessary in certain circumstances.
57 pub unsafe trait RawMutexFair
: RawMutex
{
58 /// Unlocks this mutex using a fair unlock protocol.
59 fn unlock_fair(&self);
61 /// Temporarily yields the mutex to a waiting thread if there is one.
63 /// This method is functionally equivalent to calling `unlock_fair` followed
64 /// by `lock`, however it can be much more efficient in the case where there
65 /// are no waiting threads.
72 /// Additional methods for mutexes which support locking with timeouts.
74 /// The `Duration` and `Instant` types are specified as associated types so that
75 /// this trait is usable even in `no_std` environments.
76 pub unsafe trait RawMutexTimed
: RawMutex
{
77 /// Duration type used for `try_lock_for`.
80 /// Instant type used for `try_lock_until`.
83 /// Attempts to acquire this lock until a timeout is reached.
84 fn try_lock_for(&self, timeout
: Self::Duration
) -> bool
;
86 /// Attempts to acquire this lock until a timeout is reached.
87 fn try_lock_until(&self, timeout
: Self::Instant
) -> bool
;
90 /// A mutual exclusion primitive useful for protecting shared data
92 /// This mutex will block threads waiting for the lock to become available. The
93 /// mutex can also be statically initialized or created via a `new`
94 /// constructor. Each mutex has a type parameter which represents the data that
95 /// it is protecting. The data can only be accessed through the RAII guards
96 /// returned from `lock` and `try_lock`, which guarantees that the data is only
97 /// ever accessed when the mutex is locked.
98 pub struct Mutex
<R
, T
: ?Sized
> {
103 unsafe impl<R
: RawMutex
+ Send
, T
: ?Sized
+ Send
> Send
for Mutex
<R
, T
> {}
104 unsafe impl<R
: RawMutex
+ Sync
, T
: ?Sized
+ Send
> Sync
for Mutex
<R
, T
> {}
106 impl<R
: RawMutex
, T
> Mutex
<R
, T
> {
107 /// Creates a new mutex in an unlocked state ready for use.
108 #[cfg(feature = "nightly")]
110 pub const fn new(val
: T
) -> Mutex
<R
, T
> {
113 data
: UnsafeCell
::new(val
),
117 /// Creates a new mutex in an unlocked state ready for use.
118 #[cfg(not(feature = "nightly"))]
120 pub fn new(val
: T
) -> Mutex
<R
, T
> {
123 data
: UnsafeCell
::new(val
),
127 /// Consumes this mutex, returning the underlying data.
129 pub fn into_inner(self) -> T
{
130 self.data
.into_inner()
134 impl<R
, T
> Mutex
<R
, T
> {
135 /// Creates a new mutex based on a pre-existing raw mutex.
137 /// This allows creating a mutex in a constant context on stable Rust.
139 pub const fn const_new(raw_mutex
: R
, val
: T
) -> Mutex
<R
, T
> {
142 data
: UnsafeCell
::new(val
),
147 impl<R
: RawMutex
, T
: ?Sized
> Mutex
<R
, T
> {
150 /// The lock must be held when calling this method.
152 unsafe fn guard(&self) -> MutexGuard
<'_
, R
, T
> {
159 /// Acquires a mutex, blocking the current thread until it is able to do so.
161 /// This function will block the local thread until it is available to acquire
162 /// the mutex. Upon returning, the thread is the only thread with the mutex
163 /// held. An RAII guard is returned to allow scoped unlock of the lock. When
164 /// the guard goes out of scope, the mutex will be unlocked.
166 /// Attempts to lock a mutex in the thread which already holds the lock will
167 /// result in a deadlock.
169 pub fn lock(&self) -> MutexGuard
<'_
, R
, T
> {
171 // SAFETY: The lock is held, as required.
172 unsafe { self.guard() }
175 /// Attempts to acquire this lock.
177 /// If the lock could not be acquired at this time, then `None` is returned.
178 /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
179 /// guard is dropped.
181 /// This function does not block.
183 pub fn try_lock(&self) -> Option
<MutexGuard
<'_
, R
, T
>> {
184 if self.raw
.try_lock() {
185 // SAFETY: The lock is held, as required.
186 Some(unsafe { self.guard() }
)
192 /// Returns a mutable reference to the underlying data.
194 /// Since this call borrows the `Mutex` mutably, no actual locking needs to
195 /// take place---the mutable borrow statically guarantees no locks exist.
197 pub fn get_mut(&mut self) -> &mut T
{
198 unsafe { &mut *self.data.get() }
201 /// Forcibly unlocks the mutex.
203 /// This is useful when combined with `mem::forget` to hold a lock without
204 /// the need to maintain a `MutexGuard` object alive, for example when
205 /// dealing with FFI.
209 /// This method must only be called if the current thread logically owns a
210 /// `MutexGuard` but that guard has be discarded using `mem::forget`.
211 /// Behavior is undefined if a mutex is unlocked when not locked.
213 pub unsafe fn force_unlock(&self) {
217 /// Returns the underlying raw mutex object.
219 /// Note that you will most likely need to import the `RawMutex` trait from
220 /// `lock_api` to be able to call functions on the raw mutex.
224 /// This method is unsafe because it allows unlocking a mutex while
225 /// still holding a reference to a `MutexGuard`.
227 pub unsafe fn raw(&self) -> &R
{
232 impl<R
: RawMutexFair
, T
: ?Sized
> Mutex
<R
, T
> {
233 /// Forcibly unlocks the mutex using a fair unlock procotol.
235 /// This is useful when combined with `mem::forget` to hold a lock without
236 /// the need to maintain a `MutexGuard` object alive, for example when
237 /// dealing with FFI.
241 /// This method must only be called if the current thread logically owns a
242 /// `MutexGuard` but that guard has be discarded using `mem::forget`.
243 /// Behavior is undefined if a mutex is unlocked when not locked.
245 pub unsafe fn force_unlock_fair(&self) {
246 self.raw
.unlock_fair();
250 impl<R
: RawMutexTimed
, T
: ?Sized
> Mutex
<R
, T
> {
251 /// Attempts to acquire this lock until a timeout is reached.
253 /// If the lock could not be acquired before the timeout expired, then
254 /// `None` is returned. Otherwise, an RAII guard is returned. The lock will
255 /// be unlocked when the guard is dropped.
257 pub fn try_lock_for(&self, timeout
: R
::Duration
) -> Option
<MutexGuard
<'_
, R
, T
>> {
258 if self.raw
.try_lock_for(timeout
) {
259 // SAFETY: The lock is held, as required.
260 Some(unsafe { self.guard() }
)
266 /// Attempts to acquire this lock until a timeout is reached.
268 /// If the lock could not be acquired before the timeout expired, then
269 /// `None` is returned. Otherwise, an RAII guard is returned. The lock will
270 /// be unlocked when the guard is dropped.
272 pub fn try_lock_until(&self, timeout
: R
::Instant
) -> Option
<MutexGuard
<'_
, R
, T
>> {
273 if self.raw
.try_lock_until(timeout
) {
274 // SAFETY: The lock is held, as required.
275 Some(unsafe { self.guard() }
)
282 impl<R
: RawMutex
, T
: ?Sized
+ Default
> Default
for Mutex
<R
, T
> {
284 fn default() -> Mutex
<R
, T
> {
285 Mutex
::new(Default
::default())
289 impl<R
: RawMutex
, T
> From
<T
> for Mutex
<R
, T
> {
291 fn from(t
: T
) -> Mutex
<R
, T
> {
296 impl<R
: RawMutex
, T
: ?Sized
+ fmt
::Debug
> fmt
::Debug
for Mutex
<R
, T
> {
297 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
298 match self.try_lock() {
299 Some(guard
) => f
.debug_struct("Mutex").field("data", &&*guard
).finish(),
301 struct LockedPlaceholder
;
302 impl fmt
::Debug
for LockedPlaceholder
{
303 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
304 f
.write_str("<locked>")
308 f
.debug_struct("Mutex")
309 .field("data", &LockedPlaceholder
)
316 // Copied and modified from serde
317 #[cfg(feature = "serde")]
318 impl<R
, T
> Serialize
for Mutex
<R
, T
>
321 T
: Serialize
+ ?Sized
,
323 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
327 self.lock().serialize(serializer
)
331 #[cfg(feature = "serde")]
332 impl<'de
, R
, T
> Deserialize
<'de
> for Mutex
<R
, T
>
335 T
: Deserialize
<'de
> + ?Sized
,
337 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
339 D
: Deserializer
<'de
>,
341 Deserialize
::deserialize(deserializer
).map(Mutex
::new
)
345 /// An RAII implementation of a "scoped lock" of a mutex. When this structure is
346 /// dropped (falls out of scope), the lock will be unlocked.
348 /// The data protected by the mutex can be accessed through this guard via its
349 /// `Deref` and `DerefMut` implementations.
350 #[must_use = "if unused the Mutex will immediately unlock"]
351 pub struct MutexGuard
<'a
, R
: RawMutex
, T
: ?Sized
> {
352 mutex
: &'a Mutex
<R
, T
>,
353 marker
: PhantomData
<(&'a
mut T
, R
::GuardMarker
)>,
356 unsafe impl<'a
, R
: RawMutex
+ Sync
+ 'a
, T
: ?Sized
+ Sync
+ 'a
> Sync
for MutexGuard
<'a
, R
, T
> {}
358 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> MutexGuard
<'a
, R
, T
> {
359 /// Returns a reference to the original `Mutex` object.
360 pub fn mutex(s
: &Self) -> &'a Mutex
<R
, T
> {
364 /// Makes a new `MappedMutexGuard` for a component of the locked data.
366 /// This operation cannot fail as the `MutexGuard` passed
367 /// in already locked the mutex.
369 /// This is an associated function that needs to be
370 /// used as `MutexGuard::map(...)`. A method would interfere with methods of
371 /// the same name on the contents of the locked data.
373 pub fn map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> MappedMutexGuard
<'a
, R
, U
>
375 F
: FnOnce(&mut T
) -> &mut U
,
377 let raw
= &s
.mutex
.raw
;
378 let data
= f(unsafe { &mut *s.mutex.data.get() }
);
387 /// Attempts to make a new `MappedMutexGuard` for a component of the
388 /// locked data. The original guard is returned if the closure returns `None`.
390 /// This operation cannot fail as the `MutexGuard` passed
391 /// in already locked the mutex.
393 /// This is an associated function that needs to be
394 /// used as `MutexGuard::try_map(...)`. A method would interfere with methods of
395 /// the same name on the contents of the locked data.
397 pub fn try_map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> Result
<MappedMutexGuard
<'a
, R
, U
>, Self>
399 F
: FnOnce(&mut T
) -> Option
<&mut U
>,
401 let raw
= &s
.mutex
.raw
;
402 let data
= match f(unsafe { &mut *s.mutex.data.get() }
) {
404 None
=> return Err(s
),
407 Ok(MappedMutexGuard
{
414 /// Temporarily unlocks the mutex to execute the given function.
416 /// This is safe because `&mut` guarantees that there exist no other
417 /// references to the data protected by the mutex.
419 pub fn unlocked
<F
, U
>(s
: &mut Self, f
: F
) -> U
423 s
.mutex
.raw
.unlock();
424 defer
!(s
.mutex
.raw
.lock());
429 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MutexGuard
<'a
, R
, T
> {
430 /// Unlocks the mutex using a fair unlock protocol.
432 /// By default, mutexes are unfair and allow the current thread to re-lock
433 /// the mutex before another has the chance to acquire the lock, even if
434 /// that thread has been blocked on the mutex for a long time. This is the
435 /// default because it allows much higher throughput as it avoids forcing a
436 /// context switch on every mutex unlock. This can result in one thread
437 /// acquiring a mutex many more times than other threads.
439 /// However in some cases it can be beneficial to ensure fairness by forcing
440 /// the lock to pass on to a waiting thread if there is one. This is done by
441 /// using this method instead of dropping the `MutexGuard` normally.
443 pub fn unlock_fair(s
: Self) {
444 s
.mutex
.raw
.unlock_fair();
448 /// Temporarily unlocks the mutex to execute the given function.
450 /// The mutex is unlocked using a fair unlock protocol.
452 /// This is safe because `&mut` guarantees that there exist no other
453 /// references to the data protected by the mutex.
455 pub fn unlocked_fair
<F
, U
>(s
: &mut Self, f
: F
) -> U
459 s
.mutex
.raw
.unlock_fair();
460 defer
!(s
.mutex
.raw
.lock());
464 /// Temporarily yields the mutex to a waiting thread if there is one.
466 /// This method is functionally equivalent to calling `unlock_fair` followed
467 /// by `lock`, however it can be much more efficient in the case where there
468 /// are no waiting threads.
470 pub fn bump(s
: &mut Self) {
475 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MutexGuard
<'a
, R
, T
> {
478 fn deref(&self) -> &T
{
479 unsafe { &*self.mutex.data.get() }
483 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MutexGuard
<'a
, R
, T
> {
485 fn deref_mut(&mut self) -> &mut T
{
486 unsafe { &mut *self.mutex.data.get() }
490 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MutexGuard
<'a
, R
, T
> {
493 self.mutex
.raw
.unlock();
497 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MutexGuard
<'a
, R
, T
> {
498 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
499 fmt
::Debug
::fmt(&**self, f
)
503 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
for MutexGuard
<'a
, R
, T
> {
504 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
509 #[cfg(feature = "owning_ref")]
510 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MutexGuard
<'a
, R
, T
> {}
512 /// An RAII mutex guard returned by `MutexGuard::map`, which can point to a
513 /// subfield of the protected data.
515 /// The main difference between `MappedMutexGuard` and `MutexGuard` is that the
516 /// former doesn't support temporarily unlocking and re-locking, since that
517 /// could introduce soundness issues if the locked object is modified by another
519 #[must_use = "if unused the Mutex will immediately unlock"]
520 pub struct MappedMutexGuard
<'a
, R
: RawMutex
, T
: ?Sized
> {
523 marker
: PhantomData
<&'a
mut T
>,
526 unsafe impl<'a
, R
: RawMutex
+ Sync
+ 'a
, T
: ?Sized
+ Sync
+ 'a
> Sync
527 for MappedMutexGuard
<'a
, R
, T
>
530 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Send
for MappedMutexGuard
<'a
, R
, T
> where
535 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
536 /// Makes a new `MappedMutexGuard` for a component of the locked data.
538 /// This operation cannot fail as the `MappedMutexGuard` passed
539 /// in already locked the mutex.
541 /// This is an associated function that needs to be
542 /// used as `MappedMutexGuard::map(...)`. A method would interfere with methods of
543 /// the same name on the contents of the locked data.
545 pub fn map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> MappedMutexGuard
<'a
, R
, U
>
547 F
: FnOnce(&mut T
) -> &mut U
,
550 let data
= f(unsafe { &mut *s.data }
);
559 /// Attempts to make a new `MappedMutexGuard` for a component of the
560 /// locked data. The original guard is returned if the closure returns `None`.
562 /// This operation cannot fail as the `MappedMutexGuard` passed
563 /// in already locked the mutex.
565 /// This is an associated function that needs to be
566 /// used as `MappedMutexGuard::try_map(...)`. A method would interfere with methods of
567 /// the same name on the contents of the locked data.
569 pub fn try_map
<U
: ?Sized
, F
>(s
: Self, f
: F
) -> Result
<MappedMutexGuard
<'a
, R
, U
>, Self>
571 F
: FnOnce(&mut T
) -> Option
<&mut U
>,
574 let data
= match f(unsafe { &mut *s.data }
) {
576 None
=> return Err(s
),
579 Ok(MappedMutexGuard
{
587 impl<'a
, R
: RawMutexFair
+ 'a
, T
: ?Sized
+ 'a
> MappedMutexGuard
<'a
, R
, T
> {
588 /// Unlocks the mutex using a fair unlock protocol.
590 /// By default, mutexes are unfair and allow the current thread to re-lock
591 /// the mutex before another has the chance to acquire the lock, even if
592 /// that thread has been blocked on the mutex for a long time. This is the
593 /// default because it allows much higher throughput as it avoids forcing a
594 /// context switch on every mutex unlock. This can result in one thread
595 /// acquiring a mutex many more times than other threads.
597 /// However in some cases it can be beneficial to ensure fairness by forcing
598 /// the lock to pass on to a waiting thread if there is one. This is done by
599 /// using this method instead of dropping the `MutexGuard` normally.
601 pub fn unlock_fair(s
: Self) {
607 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Deref
for MappedMutexGuard
<'a
, R
, T
> {
610 fn deref(&self) -> &T
{
611 unsafe { &*self.data }
615 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> DerefMut
for MappedMutexGuard
<'a
, R
, T
> {
617 fn deref_mut(&mut self) -> &mut T
{
618 unsafe { &mut *self.data }
622 impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> Drop
for MappedMutexGuard
<'a
, R
, T
> {
629 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Debug
+ ?Sized
+ 'a
> fmt
::Debug
for MappedMutexGuard
<'a
, R
, T
> {
630 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
631 fmt
::Debug
::fmt(&**self, f
)
635 impl<'a
, R
: RawMutex
+ 'a
, T
: fmt
::Display
+ ?Sized
+ 'a
> fmt
::Display
636 for MappedMutexGuard
<'a
, R
, T
>
638 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
643 #[cfg(feature = "owning_ref")]
644 unsafe impl<'a
, R
: RawMutex
+ 'a
, T
: ?Sized
+ 'a
> StableAddress
for MappedMutexGuard
<'a
, R
, T
> {}