From df5ba9b54bd0cd9f24b5383747ce1f502b5215a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=88=91=E5=B0=B1=E5=83=8F=E5=B1=8E=E7=9A=84=E5=80=92?= =?UTF-8?q?=E5=BD=B1?= Date: Thu, 23 Sep 2021 17:46:14 +0800 Subject: [PATCH] sync: add `blocking_lock` to `Mutex` (#4130) --- tokio/src/sync/mutex.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 6acd28b6255..95b69e6281c 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -301,6 +301,40 @@ impl Mutex { MutexGuard { lock: self } } + /// Blocking lock this mutex. When the lock has been acquired, function returns a + /// [`MutexGuard`]. + /// + /// This method is intended for use cases where you + /// need to use this mutex in asynchronous code as well as in synchronous code. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use tokio::sync::Mutex; + /// + /// #[tokio::main] + /// async fn main() { + /// let mutex = Arc::new(Mutex::new(1)); + /// + /// let mutex1 = Arc::clone(&mutex); + /// let sync_code = tokio::task::spawn_blocking(move || { + /// let mut n = mutex1.blocking_lock(); + /// *n = 2; + /// }); + /// + /// sync_code.await.unwrap(); + /// + /// let n = mutex.lock().await; + /// assert_eq!(*n, 2); + /// } + /// + /// ``` + #[cfg(feature = "sync")] + pub fn blocking_lock(&self) -> MutexGuard<'_, T> { + crate::future::block_on(self.lock()) + } + /// Locks this mutex, causing the current task to yield until the lock has /// been acquired. When the lock has been acquired, this returns an /// [`OwnedMutexGuard`].