• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![cfg_attr(not(feature = "sync"), allow(unreachable_pub, dead_code))]
2 
3 use crate::sync::batch_semaphore as semaphore;
4 
5 use std::cell::UnsafeCell;
6 use std::error::Error;
7 use std::ops::{Deref, DerefMut};
8 use std::sync::Arc;
9 use std::{fmt, marker, mem};
10 
11 /// An asynchronous `Mutex`-like type.
12 ///
13 /// This type acts similarly to [`std::sync::Mutex`], with two major
14 /// differences: [`lock`] is an async method so does not block, and the lock
15 /// guard is designed to be held across `.await` points.
16 ///
17 /// # Which kind of mutex should you use?
18 ///
19 /// Contrary to popular belief, it is ok and often preferred to use the ordinary
20 /// [`Mutex`][std] from the standard library in asynchronous code.
21 ///
22 /// The feature that the async mutex offers over the blocking mutex is the
23 /// ability to keep it locked across an `.await` point. This makes the async
24 /// mutex more expensive than the blocking mutex, so the blocking mutex should
25 /// be preferred in the cases where it can be used. The primary use case for the
26 /// async mutex is to provide shared mutable access to IO resources such as a
27 /// database connection. If the value behind the mutex is just data, it's
28 /// usually appropriate to use a blocking mutex such as the one in the standard
29 /// library or [`parking_lot`].
30 ///
31 /// Note that, although the compiler will not prevent the std `Mutex` from holding
32 /// its guard across `.await` points in situations where the task is not movable
33 /// between threads, this virtually never leads to correct concurrent code in
34 /// practice as it can easily lead to deadlocks.
35 ///
36 /// A common pattern is to wrap the `Arc<Mutex<...>>` in a struct that provides
37 /// non-async methods for performing operations on the data within, and only
38 /// lock the mutex inside these methods. The [mini-redis] example provides an
39 /// illustration of this pattern.
40 ///
41 /// Additionally, when you _do_ want shared access to an IO resource, it is
42 /// often better to spawn a task to manage the IO resource, and to use message
43 /// passing to communicate with that task.
44 ///
45 /// [std]: std::sync::Mutex
46 /// [`parking_lot`]: https://docs.rs/parking_lot
47 /// [mini-redis]: https://github.com/tokio-rs/mini-redis/blob/master/src/db.rs
48 ///
49 /// # Examples:
50 ///
51 /// ```rust,no_run
52 /// use tokio::sync::Mutex;
53 /// use std::sync::Arc;
54 ///
55 /// #[tokio::main]
56 /// async fn main() {
57 ///     let data1 = Arc::new(Mutex::new(0));
58 ///     let data2 = Arc::clone(&data1);
59 ///
60 ///     tokio::spawn(async move {
61 ///         let mut lock = data2.lock().await;
62 ///         *lock += 1;
63 ///     });
64 ///
65 ///     let mut lock = data1.lock().await;
66 ///     *lock += 1;
67 /// }
68 /// ```
69 ///
70 ///
71 /// ```rust,no_run
72 /// use tokio::sync::Mutex;
73 /// use std::sync::Arc;
74 ///
75 /// #[tokio::main]
76 /// async fn main() {
77 ///     let count = Arc::new(Mutex::new(0));
78 ///
79 ///     for i in 0..5 {
80 ///         let my_count = Arc::clone(&count);
81 ///         tokio::spawn(async move {
82 ///             for j in 0..10 {
83 ///                 let mut lock = my_count.lock().await;
84 ///                 *lock += 1;
85 ///                 println!("{} {} {}", i, j, lock);
86 ///             }
87 ///         });
88 ///     }
89 ///
90 ///     loop {
91 ///         if *count.lock().await >= 50 {
92 ///             break;
93 ///         }
94 ///     }
95 ///     println!("Count hit 50.");
96 /// }
97 /// ```
98 /// There are a few things of note here to pay attention to in this example.
99 /// 1. The mutex is wrapped in an [`Arc`] to allow it to be shared across
100 ///    threads.
101 /// 2. Each spawned task obtains a lock and releases it on every iteration.
102 /// 3. Mutation of the data protected by the Mutex is done by de-referencing
103 ///    the obtained lock as seen on lines 12 and 19.
104 ///
105 /// Tokio's Mutex works in a simple FIFO (first in, first out) style where all
106 /// calls to [`lock`] complete in the order they were performed. In that way the
107 /// Mutex is "fair" and predictable in how it distributes the locks to inner
108 /// data. Locks are released and reacquired after every iteration, so basically,
109 /// each thread goes to the back of the line after it increments the value once.
110 /// Note that there's some unpredictability to the timing between when the
111 /// threads are started, but once they are going they alternate predictably.
112 /// Finally, since there is only a single valid lock at any given time, there is
113 /// no possibility of a race condition when mutating the inner value.
114 ///
115 /// Note that in contrast to [`std::sync::Mutex`], this implementation does not
116 /// poison the mutex when a thread holding the [`MutexGuard`] panics. In such a
117 /// case, the mutex will be unlocked. If the panic is caught, this might leave
118 /// the data protected by the mutex in an inconsistent state.
119 ///
120 /// [`Mutex`]: struct@Mutex
121 /// [`MutexGuard`]: struct@MutexGuard
122 /// [`Arc`]: struct@std::sync::Arc
123 /// [`std::sync::Mutex`]: struct@std::sync::Mutex
124 /// [`Send`]: trait@std::marker::Send
125 /// [`lock`]: method@Mutex::lock
126 pub struct Mutex<T: ?Sized> {
127     s: semaphore::Semaphore,
128     c: UnsafeCell<T>,
129 }
130 
131 /// A handle to a held `Mutex`. The guard can be held across any `.await` point
132 /// as it is [`Send`].
133 ///
134 /// As long as you have this guard, you have exclusive access to the underlying
135 /// `T`. The guard internally borrows the `Mutex`, so the mutex will not be
136 /// dropped while a guard exists.
137 ///
138 /// The lock is automatically released whenever the guard is dropped, at which
139 /// point `lock` will succeed yet again.
140 pub struct MutexGuard<'a, T: ?Sized> {
141     lock: &'a Mutex<T>,
142 }
143 
144 /// An owned handle to a held `Mutex`.
145 ///
146 /// This guard is only available from a `Mutex` that is wrapped in an [`Arc`]. It
147 /// is identical to `MutexGuard`, except that rather than borrowing the `Mutex`,
148 /// it clones the `Arc`, incrementing the reference count. This means that
149 /// unlike `MutexGuard`, it will have the `'static` lifetime.
150 ///
151 /// As long as you have this guard, you have exclusive access to the underlying
152 /// `T`. The guard internally keeps a reference-counted pointer to the original
153 /// `Mutex`, so even if the lock goes away, the guard remains valid.
154 ///
155 /// The lock is automatically released whenever the guard is dropped, at which
156 /// point `lock` will succeed yet again.
157 ///
158 /// [`Arc`]: std::sync::Arc
159 pub struct OwnedMutexGuard<T: ?Sized> {
160     lock: Arc<Mutex<T>>,
161 }
162 
163 /// A handle to a held `Mutex` that has had a function applied to it via [`MutexGuard::map`].
164 ///
165 /// This can be used to hold a subfield of the protected data.
166 ///
167 /// [`MutexGuard::map`]: method@MutexGuard::map
168 #[must_use = "if unused the Mutex will immediately unlock"]
169 pub struct MappedMutexGuard<'a, T: ?Sized> {
170     s: &'a semaphore::Semaphore,
171     data: *mut T,
172     // Needed to tell the borrow checker that we are holding a `&mut T`
173     marker: marker::PhantomData<&'a mut T>,
174 }
175 
176 // As long as T: Send, it's fine to send and share Mutex<T> between threads.
177 // If T was not Send, sending and sharing a Mutex<T> would be bad, since you can
178 // access T through Mutex<T>.
179 unsafe impl<T> Send for Mutex<T> where T: ?Sized + Send {}
180 unsafe impl<T> Sync for Mutex<T> where T: ?Sized + Send {}
181 unsafe impl<T> Sync for MutexGuard<'_, T> where T: ?Sized + Send + Sync {}
182 unsafe impl<T> Sync for OwnedMutexGuard<T> where T: ?Sized + Send + Sync {}
183 unsafe impl<'a, T> Sync for MappedMutexGuard<'a, T> where T: ?Sized + Sync + 'a {}
184 unsafe impl<'a, T> Send for MappedMutexGuard<'a, T> where T: ?Sized + Send + 'a {}
185 
186 /// Error returned from the [`Mutex::try_lock`], [`RwLock::try_read`] and
187 /// [`RwLock::try_write`] functions.
188 ///
189 /// `Mutex::try_lock` operation will only fail if the mutex is already locked.
190 ///
191 /// `RwLock::try_read` operation will only fail if the lock is currently held
192 /// by an exclusive writer.
193 ///
194 /// `RwLock::try_write` operation will if lock is held by any reader or by an
195 /// exclusive writer.
196 ///
197 /// [`Mutex::try_lock`]: Mutex::try_lock
198 /// [`RwLock::try_read`]: fn@super::RwLock::try_read
199 /// [`RwLock::try_write`]: fn@super::RwLock::try_write
200 #[derive(Debug)]
201 pub struct TryLockError(pub(super) ());
202 
203 impl fmt::Display for TryLockError {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result204     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
205         write!(fmt, "operation would block")
206     }
207 }
208 
209 impl Error for TryLockError {}
210 
211 #[test]
212 #[cfg(not(loom))]
bounds()213 fn bounds() {
214     fn check_send<T: Send>() {}
215     fn check_unpin<T: Unpin>() {}
216     // This has to take a value, since the async fn's return type is unnameable.
217     fn check_send_sync_val<T: Send + Sync>(_t: T) {}
218     fn check_send_sync<T: Send + Sync>() {}
219     fn check_static<T: 'static>() {}
220     fn check_static_val<T: 'static>(_t: T) {}
221 
222     check_send::<MutexGuard<'_, u32>>();
223     check_send::<OwnedMutexGuard<u32>>();
224     check_unpin::<Mutex<u32>>();
225     check_send_sync::<Mutex<u32>>();
226     check_static::<OwnedMutexGuard<u32>>();
227 
228     let mutex = Mutex::new(1);
229     check_send_sync_val(mutex.lock());
230     let arc_mutex = Arc::new(Mutex::new(1));
231     check_send_sync_val(arc_mutex.clone().lock_owned());
232     check_static_val(arc_mutex.lock_owned());
233 }
234 
235 impl<T: ?Sized> Mutex<T> {
236     /// Creates a new lock in an unlocked state ready for use.
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// use tokio::sync::Mutex;
242     ///
243     /// let lock = Mutex::new(5);
244     /// ```
new(t: T) -> Self where T: Sized,245     pub fn new(t: T) -> Self
246     where
247         T: Sized,
248     {
249         Self {
250             c: UnsafeCell::new(t),
251             s: semaphore::Semaphore::new(1),
252         }
253     }
254 
255     /// Creates a new lock in an unlocked state ready for use.
256     ///
257     /// # Examples
258     ///
259     /// ```
260     /// use tokio::sync::Mutex;
261     ///
262     /// static LOCK: Mutex<i32> = Mutex::const_new(5);
263     /// ```
264     #[cfg(all(feature = "parking_lot", not(all(loom, test)),))]
265     #[cfg_attr(docsrs, doc(cfg(feature = "parking_lot")))]
const_new(t: T) -> Self where T: Sized,266     pub const fn const_new(t: T) -> Self
267     where
268         T: Sized,
269     {
270         Self {
271             c: UnsafeCell::new(t),
272             s: semaphore::Semaphore::const_new(1),
273         }
274     }
275 
276     /// Locks this mutex, causing the current task to yield until the lock has
277     /// been acquired.  When the lock has been acquired, function returns a
278     /// [`MutexGuard`].
279     ///
280     /// # Cancel safety
281     ///
282     /// This method uses a queue to fairly distribute locks in the order they
283     /// were requested. Cancelling a call to `lock` makes you lose your place in
284     /// the queue.
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// use tokio::sync::Mutex;
290     ///
291     /// #[tokio::main]
292     /// async fn main() {
293     ///     let mutex = Mutex::new(1);
294     ///
295     ///     let mut n = mutex.lock().await;
296     ///     *n = 2;
297     /// }
298     /// ```
lock(&self) -> MutexGuard<'_, T>299     pub async fn lock(&self) -> MutexGuard<'_, T> {
300         self.acquire().await;
301         MutexGuard { lock: self }
302     }
303 
304     /// Blocking lock this mutex. When the lock has been acquired, function returns a
305     /// [`MutexGuard`].
306     ///
307     /// This method is intended for use cases where you
308     /// need to use this mutex in asynchronous code as well as in synchronous code.
309     ///
310     /// # Examples
311     ///
312     /// ```
313     /// use std::sync::Arc;
314     /// use tokio::sync::Mutex;
315     ///
316     /// #[tokio::main]
317     /// async fn main() {
318     ///     let mutex =  Arc::new(Mutex::new(1));
319     ///
320     ///     let mutex1 = Arc::clone(&mutex);
321     ///     let sync_code = tokio::task::spawn_blocking(move || {
322     ///         let mut n = mutex1.blocking_lock();
323     ///         *n = 2;
324     ///     });
325     ///
326     ///     sync_code.await.unwrap();
327     ///
328     ///     let n = mutex.lock().await;
329     ///     assert_eq!(*n, 2);
330     /// }
331     ///
332     /// ```
333     #[cfg(feature = "sync")]
blocking_lock(&self) -> MutexGuard<'_, T>334     pub fn blocking_lock(&self) -> MutexGuard<'_, T> {
335         crate::future::block_on(self.lock())
336     }
337 
338     /// Locks this mutex, causing the current task to yield until the lock has
339     /// been acquired. When the lock has been acquired, this returns an
340     /// [`OwnedMutexGuard`].
341     ///
342     /// This method is identical to [`Mutex::lock`], except that the returned
343     /// guard references the `Mutex` with an [`Arc`] rather than by borrowing
344     /// it. Therefore, the `Mutex` must be wrapped in an `Arc` to call this
345     /// method, and the guard will live for the `'static` lifetime, as it keeps
346     /// the `Mutex` alive by holding an `Arc`.
347     ///
348     /// # Cancel safety
349     ///
350     /// This method uses a queue to fairly distribute locks in the order they
351     /// were requested. Cancelling a call to `lock_owned` makes you lose your
352     /// place in the queue.
353     ///
354     /// # Examples
355     ///
356     /// ```
357     /// use tokio::sync::Mutex;
358     /// use std::sync::Arc;
359     ///
360     /// #[tokio::main]
361     /// async fn main() {
362     ///     let mutex = Arc::new(Mutex::new(1));
363     ///
364     ///     let mut n = mutex.clone().lock_owned().await;
365     ///     *n = 2;
366     /// }
367     /// ```
368     ///
369     /// [`Arc`]: std::sync::Arc
lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T>370     pub async fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T> {
371         self.acquire().await;
372         OwnedMutexGuard { lock: self }
373     }
374 
acquire(&self)375     async fn acquire(&self) {
376         self.s.acquire(1).await.unwrap_or_else(|_| {
377             // The semaphore was closed. but, we never explicitly close it, and
378             // we own it exclusively, which means that this can never happen.
379             unreachable!()
380         });
381     }
382 
383     /// Attempts to acquire the lock, and returns [`TryLockError`] if the
384     /// lock is currently held somewhere else.
385     ///
386     /// [`TryLockError`]: TryLockError
387     /// # Examples
388     ///
389     /// ```
390     /// use tokio::sync::Mutex;
391     /// # async fn dox() -> Result<(), tokio::sync::TryLockError> {
392     ///
393     /// let mutex = Mutex::new(1);
394     ///
395     /// let n = mutex.try_lock()?;
396     /// assert_eq!(*n, 1);
397     /// # Ok(())
398     /// # }
399     /// ```
try_lock(&self) -> Result<MutexGuard<'_, T>, TryLockError>400     pub fn try_lock(&self) -> Result<MutexGuard<'_, T>, TryLockError> {
401         match self.s.try_acquire(1) {
402             Ok(_) => Ok(MutexGuard { lock: self }),
403             Err(_) => Err(TryLockError(())),
404         }
405     }
406 
407     /// Returns a mutable reference to the underlying data.
408     ///
409     /// Since this call borrows the `Mutex` mutably, no actual locking needs to
410     /// take place -- the mutable borrow statically guarantees no locks exist.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// use tokio::sync::Mutex;
416     ///
417     /// fn main() {
418     ///     let mut mutex = Mutex::new(1);
419     ///
420     ///     let n = mutex.get_mut();
421     ///     *n = 2;
422     /// }
423     /// ```
get_mut(&mut self) -> &mut T424     pub fn get_mut(&mut self) -> &mut T {
425         unsafe {
426             // Safety: This is https://github.com/rust-lang/rust/pull/76936
427             &mut *self.c.get()
428         }
429     }
430 
431     /// Attempts to acquire the lock, and returns [`TryLockError`] if the lock
432     /// is currently held somewhere else.
433     ///
434     /// This method is identical to [`Mutex::try_lock`], except that the
435     /// returned  guard references the `Mutex` with an [`Arc`] rather than by
436     /// borrowing it. Therefore, the `Mutex` must be wrapped in an `Arc` to call
437     /// this method, and the guard will live for the `'static` lifetime, as it
438     /// keeps the `Mutex` alive by holding an `Arc`.
439     ///
440     /// [`TryLockError`]: TryLockError
441     /// [`Arc`]: std::sync::Arc
442     /// # Examples
443     ///
444     /// ```
445     /// use tokio::sync::Mutex;
446     /// use std::sync::Arc;
447     /// # async fn dox() -> Result<(), tokio::sync::TryLockError> {
448     ///
449     /// let mutex = Arc::new(Mutex::new(1));
450     ///
451     /// let n = mutex.clone().try_lock_owned()?;
452     /// assert_eq!(*n, 1);
453     /// # Ok(())
454     /// # }
try_lock_owned(self: Arc<Self>) -> Result<OwnedMutexGuard<T>, TryLockError>455     pub fn try_lock_owned(self: Arc<Self>) -> Result<OwnedMutexGuard<T>, TryLockError> {
456         match self.s.try_acquire(1) {
457             Ok(_) => Ok(OwnedMutexGuard { lock: self }),
458             Err(_) => Err(TryLockError(())),
459         }
460     }
461 
462     /// Consumes the mutex, returning the underlying data.
463     /// # Examples
464     ///
465     /// ```
466     /// use tokio::sync::Mutex;
467     ///
468     /// #[tokio::main]
469     /// async fn main() {
470     ///     let mutex = Mutex::new(1);
471     ///
472     ///     let n = mutex.into_inner();
473     ///     assert_eq!(n, 1);
474     /// }
475     /// ```
into_inner(self) -> T where T: Sized,476     pub fn into_inner(self) -> T
477     where
478         T: Sized,
479     {
480         self.c.into_inner()
481     }
482 }
483 
484 impl<T> From<T> for Mutex<T> {
from(s: T) -> Self485     fn from(s: T) -> Self {
486         Self::new(s)
487     }
488 }
489 
490 impl<T> Default for Mutex<T>
491 where
492     T: Default,
493 {
default() -> Self494     fn default() -> Self {
495         Self::new(T::default())
496     }
497 }
498 
499 impl<T: ?Sized> std::fmt::Debug for Mutex<T>
500 where
501     T: std::fmt::Debug,
502 {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result503     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
504         let mut d = f.debug_struct("Mutex");
505         match self.try_lock() {
506             Ok(inner) => d.field("data", &&*inner),
507             Err(_) => d.field("data", &format_args!("<locked>")),
508         };
509         d.finish()
510     }
511 }
512 
513 // === impl MutexGuard ===
514 
515 impl<'a, T: ?Sized> MutexGuard<'a, T> {
516     /// Makes a new [`MappedMutexGuard`] for a component of the locked data.
517     ///
518     /// This operation cannot fail as the [`MutexGuard`] passed in already locked the mutex.
519     ///
520     /// This is an associated function that needs to be used as `MutexGuard::map(...)`. A method
521     /// would interfere with methods of the same name on the contents of the locked data.
522     ///
523     /// # Examples
524     ///
525     /// ```
526     /// use tokio::sync::{Mutex, MutexGuard};
527     ///
528     /// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
529     /// struct Foo(u32);
530     ///
531     /// # #[tokio::main]
532     /// # async fn main() {
533     /// let foo = Mutex::new(Foo(1));
534     ///
535     /// {
536     ///     let mut mapped = MutexGuard::map(foo.lock().await, |f| &mut f.0);
537     ///     *mapped = 2;
538     /// }
539     ///
540     /// assert_eq!(Foo(2), *foo.lock().await);
541     /// # }
542     /// ```
543     ///
544     /// [`MutexGuard`]: struct@MutexGuard
545     /// [`MappedMutexGuard`]: struct@MappedMutexGuard
546     #[inline]
map<U, F>(mut this: Self, f: F) -> MappedMutexGuard<'a, U> where F: FnOnce(&mut T) -> &mut U,547     pub fn map<U, F>(mut this: Self, f: F) -> MappedMutexGuard<'a, U>
548     where
549         F: FnOnce(&mut T) -> &mut U,
550     {
551         let data = f(&mut *this) as *mut U;
552         let s = &this.lock.s;
553         mem::forget(this);
554         MappedMutexGuard {
555             s,
556             data,
557             marker: marker::PhantomData,
558         }
559     }
560 
561     /// Attempts to make a new [`MappedMutexGuard`] for a component of the locked data. The
562     /// original guard is returned if the closure returns `None`.
563     ///
564     /// This operation cannot fail as the [`MutexGuard`] passed in already locked the mutex.
565     ///
566     /// This is an associated function that needs to be used as `MutexGuard::try_map(...)`. A
567     /// method would interfere with methods of the same name on the contents of the locked data.
568     ///
569     /// # Examples
570     ///
571     /// ```
572     /// use tokio::sync::{Mutex, MutexGuard};
573     ///
574     /// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
575     /// struct Foo(u32);
576     ///
577     /// # #[tokio::main]
578     /// # async fn main() {
579     /// let foo = Mutex::new(Foo(1));
580     ///
581     /// {
582     ///     let mut mapped = MutexGuard::try_map(foo.lock().await, |f| Some(&mut f.0))
583     ///         .expect("should not fail");
584     ///     *mapped = 2;
585     /// }
586     ///
587     /// assert_eq!(Foo(2), *foo.lock().await);
588     /// # }
589     /// ```
590     ///
591     /// [`MutexGuard`]: struct@MutexGuard
592     /// [`MappedMutexGuard`]: struct@MappedMutexGuard
593     #[inline]
try_map<U, F>(mut this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self> where F: FnOnce(&mut T) -> Option<&mut U>,594     pub fn try_map<U, F>(mut this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
595     where
596         F: FnOnce(&mut T) -> Option<&mut U>,
597     {
598         let data = match f(&mut *this) {
599             Some(data) => data as *mut U,
600             None => return Err(this),
601         };
602         let s = &this.lock.s;
603         mem::forget(this);
604         Ok(MappedMutexGuard {
605             s,
606             data,
607             marker: marker::PhantomData,
608         })
609     }
610 
611     /// Returns a reference to the original `Mutex`.
612     ///
613     /// ```
614     /// use tokio::sync::{Mutex, MutexGuard};
615     ///
616     /// async fn unlock_and_relock<'l>(guard: MutexGuard<'l, u32>) -> MutexGuard<'l, u32> {
617     ///     println!("1. contains: {:?}", *guard);
618     ///     let mutex = MutexGuard::mutex(&guard);
619     ///     drop(guard);
620     ///     let guard = mutex.lock().await;
621     ///     println!("2. contains: {:?}", *guard);
622     ///     guard
623     /// }
624     /// #
625     /// # #[tokio::main]
626     /// # async fn main() {
627     /// #     let mutex = Mutex::new(0u32);
628     /// #     let guard = mutex.lock().await;
629     /// #     unlock_and_relock(guard).await;
630     /// # }
631     /// ```
632     #[inline]
mutex(this: &Self) -> &'a Mutex<T>633     pub fn mutex(this: &Self) -> &'a Mutex<T> {
634         this.lock
635     }
636 }
637 
638 impl<T: ?Sized> Drop for MutexGuard<'_, T> {
drop(&mut self)639     fn drop(&mut self) {
640         self.lock.s.release(1)
641     }
642 }
643 
644 impl<T: ?Sized> Deref for MutexGuard<'_, T> {
645     type Target = T;
deref(&self) -> &Self::Target646     fn deref(&self) -> &Self::Target {
647         unsafe { &*self.lock.c.get() }
648     }
649 }
650 
651 impl<T: ?Sized> DerefMut for MutexGuard<'_, T> {
deref_mut(&mut self) -> &mut Self::Target652     fn deref_mut(&mut self) -> &mut Self::Target {
653         unsafe { &mut *self.lock.c.get() }
654     }
655 }
656 
657 impl<T: ?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result658     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
659         fmt::Debug::fmt(&**self, f)
660     }
661 }
662 
663 impl<T: ?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result664     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
665         fmt::Display::fmt(&**self, f)
666     }
667 }
668 
669 // === impl OwnedMutexGuard ===
670 
671 impl<T: ?Sized> OwnedMutexGuard<T> {
672     /// Returns a reference to the original `Arc<Mutex>`.
673     ///
674     /// ```
675     /// use std::sync::Arc;
676     /// use tokio::sync::{Mutex, OwnedMutexGuard};
677     ///
678     /// async fn unlock_and_relock(guard: OwnedMutexGuard<u32>) -> OwnedMutexGuard<u32> {
679     ///     println!("1. contains: {:?}", *guard);
680     ///     let mutex: Arc<Mutex<u32>> = OwnedMutexGuard::mutex(&guard).clone();
681     ///     drop(guard);
682     ///     let guard = mutex.lock_owned().await;
683     ///     println!("2. contains: {:?}", *guard);
684     ///     guard
685     /// }
686     /// #
687     /// # #[tokio::main]
688     /// # async fn main() {
689     /// #     let mutex = Arc::new(Mutex::new(0u32));
690     /// #     let guard = mutex.lock_owned().await;
691     /// #     unlock_and_relock(guard).await;
692     /// # }
693     /// ```
694     #[inline]
mutex(this: &Self) -> &Arc<Mutex<T>>695     pub fn mutex(this: &Self) -> &Arc<Mutex<T>> {
696         &this.lock
697     }
698 }
699 
700 impl<T: ?Sized> Drop for OwnedMutexGuard<T> {
drop(&mut self)701     fn drop(&mut self) {
702         self.lock.s.release(1)
703     }
704 }
705 
706 impl<T: ?Sized> Deref for OwnedMutexGuard<T> {
707     type Target = T;
deref(&self) -> &Self::Target708     fn deref(&self) -> &Self::Target {
709         unsafe { &*self.lock.c.get() }
710     }
711 }
712 
713 impl<T: ?Sized> DerefMut for OwnedMutexGuard<T> {
deref_mut(&mut self) -> &mut Self::Target714     fn deref_mut(&mut self) -> &mut Self::Target {
715         unsafe { &mut *self.lock.c.get() }
716     }
717 }
718 
719 impl<T: ?Sized + fmt::Debug> fmt::Debug for OwnedMutexGuard<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result720     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721         fmt::Debug::fmt(&**self, f)
722     }
723 }
724 
725 impl<T: ?Sized + fmt::Display> fmt::Display for OwnedMutexGuard<T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result726     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
727         fmt::Display::fmt(&**self, f)
728     }
729 }
730 
731 // === impl MappedMutexGuard ===
732 
733 impl<'a, T: ?Sized> MappedMutexGuard<'a, T> {
734     /// Makes a new [`MappedMutexGuard`] for a component of the locked data.
735     ///
736     /// This operation cannot fail as the [`MappedMutexGuard`] passed in already locked the mutex.
737     ///
738     /// This is an associated function that needs to be used as `MappedMutexGuard::map(...)`. A
739     /// method would interfere with methods of the same name on the contents of the locked data.
740     ///
741     /// [`MappedMutexGuard`]: struct@MappedMutexGuard
742     #[inline]
map<U, F>(mut this: Self, f: F) -> MappedMutexGuard<'a, U> where F: FnOnce(&mut T) -> &mut U,743     pub fn map<U, F>(mut this: Self, f: F) -> MappedMutexGuard<'a, U>
744     where
745         F: FnOnce(&mut T) -> &mut U,
746     {
747         let data = f(&mut *this) as *mut U;
748         let s = this.s;
749         mem::forget(this);
750         MappedMutexGuard {
751             s,
752             data,
753             marker: marker::PhantomData,
754         }
755     }
756 
757     /// Attempts to make a new [`MappedMutexGuard`] for a component of the locked data. The
758     /// original guard is returned if the closure returns `None`.
759     ///
760     /// This operation cannot fail as the [`MappedMutexGuard`] passed in already locked the mutex.
761     ///
762     /// This is an associated function that needs to be used as `MappedMutexGuard::try_map(...)`. A
763     /// method would interfere with methods of the same name on the contents of the locked data.
764     ///
765     /// [`MappedMutexGuard`]: struct@MappedMutexGuard
766     #[inline]
try_map<U, F>(mut this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self> where F: FnOnce(&mut T) -> Option<&mut U>,767     pub fn try_map<U, F>(mut this: Self, f: F) -> Result<MappedMutexGuard<'a, U>, Self>
768     where
769         F: FnOnce(&mut T) -> Option<&mut U>,
770     {
771         let data = match f(&mut *this) {
772             Some(data) => data as *mut U,
773             None => return Err(this),
774         };
775         let s = this.s;
776         mem::forget(this);
777         Ok(MappedMutexGuard {
778             s,
779             data,
780             marker: marker::PhantomData,
781         })
782     }
783 }
784 
785 impl<'a, T: ?Sized> Drop for MappedMutexGuard<'a, T> {
drop(&mut self)786     fn drop(&mut self) {
787         self.s.release(1)
788     }
789 }
790 
791 impl<'a, T: ?Sized> Deref for MappedMutexGuard<'a, T> {
792     type Target = T;
deref(&self) -> &Self::Target793     fn deref(&self) -> &Self::Target {
794         unsafe { &*self.data }
795     }
796 }
797 
798 impl<'a, T: ?Sized> DerefMut for MappedMutexGuard<'a, T> {
deref_mut(&mut self) -> &mut Self::Target799     fn deref_mut(&mut self) -> &mut Self::Target {
800         unsafe { &mut *self.data }
801     }
802 }
803 
804 impl<'a, T: ?Sized + fmt::Debug> fmt::Debug for MappedMutexGuard<'a, T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result805     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806         fmt::Debug::fmt(&**self, f)
807     }
808 }
809 
810 impl<'a, T: ?Sized + fmt::Display> fmt::Display for MappedMutexGuard<'a, T> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result811     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
812         fmt::Display::fmt(&**self, f)
813     }
814 }
815