Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sync: add blocking_lock for mutex #4130

Merged
merged 3 commits into from Sep 23, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 35 additions & 0 deletions tokio/src/sync/mutex.rs
Expand Up @@ -301,6 +301,41 @@ impl<T: ?Sized> Mutex<T> {
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::thread;
/// 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 = thread::spawn(move || {
/// let mut n = mutex1.blocking_lock();
/// *n = 2;
/// });
///
/// sync_code.join().unwrap();
hi-rustin marked this conversation as resolved.
Show resolved Hide resolved
///
/// 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`].
Expand Down