From d685bceb030ac7e77446a5ac65e482c6f9612048 Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Mon, 20 Jul 2020 19:15:15 +0200 Subject: sync: "which kind of mutex?" section added to doc (#2658) --- tokio/src/sync/mutex.rs | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) (limited to 'tokio/src/sync/mutex.rs') diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index c5f839ee..642058be 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -9,17 +9,35 @@ use std::sync::Arc; /// An asynchronous `Mutex`-like type. /// /// This type acts similarly to an asynchronous [`std::sync::Mutex`], with one -/// major difference: [`lock`] does not block. Another difference is that the -/// lock guard can be held across await points. +/// major difference: [`lock`] does not block and the lock guard can be held +/// across await points. /// -/// There are some situations where you should prefer the mutex from the -/// standard library. Generally this is the case if: +/// # Which kind of mutex should you use? /// -/// 1. The lock does not need to be held across await points. -/// 2. The duration of any single lock is near-instant. +/// Contrary to popular belief, it is ok and often preferred to use the ordinary +/// [`Mutex`][std] from the standard library in asynchronous code. This section +/// will help you decide on which kind of mutex you should use. /// -/// On the other hand, the Tokio mutex is for the situation where the lock -/// needs to be held for longer periods of time, or across await points. +/// The primary use case of the async mutex is to provide shared mutable access +/// to IO resources such as a database connection. If the data stored behind the +/// mutex is just data, it is often better to use a blocking mutex such as the +/// one in the standard library or [`parking_lot`]. This is because the feature +/// that the async mutex offers over the blocking mutex is that it is possible +/// to keep the mutex locked across an `.await` point, which is rarely necessary +/// for data. +/// +/// A common pattern is to wrap the `Arc>` in a struct that provides +/// non-async methods for performing operations on the data within, and only +/// lock the mutex inside these methods. The [mini-redis] example provides an +/// illustration of this pattern. +/// +/// Additionally, when you _do_ want shared access to an IO resource, it is +/// often better to spawn a task to manage the IO resource, and to use message +/// passing to communicate with that task. +/// +/// [std]: std::sync::Mutex +/// [`parking_lot`]: https://docs.rs/parking_lot +/// [mini-redis]: https://github.com/tokio-rs/mini-redis/blob/master/src/db.rs /// /// # Examples: /// -- cgit v1.2.3