From c632337e6f94013d9d39495f1d442351e6fbf6b6 Mon Sep 17 00:00:00 2001 From: "Michael P. Jung" Date: Fri, 6 Dec 2019 23:30:02 +0100 Subject: sync: fix Mutex when lock future dropped before complete (#1902) The bug caused the mutex to reach a state where it is locked and cannot be unlocked. Fixes #1898 --- tokio/src/sync/mutex.rs | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) (limited to 'tokio/src/sync/mutex.rs') diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index b06f22b4..474f5368 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -86,29 +86,24 @@ impl Mutex { /// A future that resolves on acquiring the lock and returns the `MutexGuard`. pub async fn lock(&self) -> MutexGuard<'_, T> { - let mut permit = semaphore::Permit::new(); - poll_fn(|cx| permit.poll_acquire(cx, &self.s)) + let mut guard = MutexGuard { + lock: self, + permit: semaphore::Permit::new(), + }; + poll_fn(|cx| guard.permit.poll_acquire(cx, &self.s)) .await .unwrap_or_else(|_| { // The semaphore was closed. but, we never explicitly close it, and we have a // handle to it through the Arc, which means that this can never happen. unreachable!() }); - - MutexGuard { lock: self, permit } + guard } } impl<'a, T> Drop for MutexGuard<'a, T> { fn drop(&mut self) { - if self.permit.is_acquired() { - self.permit.release(&self.lock.s); - } else if ::std::thread::panicking() { - // A guard _should_ always hold its permit, but if the thread is already panicking, - // we don't want to generate a panic-while-panicing, since that's just unhelpful! - } else { - unreachable!("Permit not held when MutexGuard was dropped") - } + self.permit.release(&self.lock.s); } } -- cgit v1.2.3