Skip to content

Commit

Permalink
bugfix: Fix missed notification in Mutex example
Browse files Browse the repository at this point in the history
I forgot to run notify() when I rewrote this example without unsafe
code. It looks like it prevents deadlocks in this mutex implementation.

I believe this fixes #143.

Signed-off-by: John Nunley <[email protected]>
  • Loading branch information
notgull committed Nov 1, 2024
1 parent a00a427 commit 633b2c6
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions examples/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ mod example {

/// Attempts to acquire a lock.
fn try_lock(&self) -> Option<MutexGuard<'_, T>> {
self.data.try_lock().map(MutexGuard)
self.data.try_lock().map(|l| MutexGuard {
lock_ops: &self.lock_ops,
locked: Some(l),
})
}

/// Blocks until a lock is acquired.
Expand Down Expand Up @@ -107,19 +110,29 @@ mod example {
}

/// A guard holding a lock.
struct MutexGuard<'a, T>(Locked<'a, T>);
struct MutexGuard<'a, T> {
lock_ops: &'a Event,
locked: Option<Locked<'a, T>>,
}

impl<T> Deref for MutexGuard<'_, T> {
type Target = T;

fn deref(&self) -> &T {
&self.0
self.locked.as_deref().unwrap()
}
}

impl<T> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
self.locked.as_deref_mut().unwrap()
}
}

impl<T> Drop for MutexGuard<'_, T> {
fn drop(&mut self) {
self.locked = None;
self.lock_ops.notify(1);
}
}

Expand Down

0 comments on commit 633b2c6

Please sign in to comment.