Skip to content

Rwlock try upgrade #138560

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions library/std/src/sync/poison/rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,6 +918,24 @@ impl<'a, T: ?Sized> RwLockReadGuard<'a, T> {
None => Err(orig),
}
}

#[unstable(feature = "rwlock_try_upgrade", issue = "138559")]
pub fn try_upgrade(orig: Self) -> Result<RwLockWriteGuard<'a, T>, RwLockReadGuard<'a, T>> {
let rwl = &RwLock {
data: UnsafeCell::new(orig.data.as_ptr().read()),
poison: poison::Flag::new(),
inner: *orig.inner_lock,
};

// don't call the destructor
forget(orig);

// SAFETY: We have ownership of the read guard, so it must be in read mode already
match unsafe { rwl.inner.try_upgrade() } {
true => Ok(RwLockWriteGuard::new(rwl).unwrap_or_else(PoisonError::into_inner)),
false => Err(RwLockReadGuard::new(rwl).unwrap_or_else(PoisonError::into_inner)),
}
}
}

impl<'a, T: ?Sized> MappedRwLockReadGuard<'a, T> {
Expand Down
18 changes: 18 additions & 0 deletions library/std/src/sys/sync/rwlock/futex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ fn is_write_locked(state: Primitive) -> bool {
state & MASK == WRITE_LOCKED
}

#[inline]
fn is_read_locked(state: Primitive) -> bool {
state & MASK == READ_LOCKED
}

#[inline]
fn has_readers_waiting(state: Primitive) -> bool {
state & READERS_WAITING != 0
Expand Down Expand Up @@ -205,6 +210,19 @@ impl RwLock {
}
}

/// # Safety
///
/// The 'RwLock' must be read-locked in order to call this. Calling this function in a loop
/// in at least 2 threads will deadlock.
#[inline]
pub unsafe fn try_upgrade(&self) -> bool {
debg_assert!(
is_read_locked(self.state),
"RwLock must be read locked to call `try_upgrade`"
);
self.state.compare_exchange(READ_LOCKED, WRITE_LOCKED, Acquire, Relaxed).is_ok()
}

#[cold]
fn write_contended(&self) {
let mut state = self.spin_write();
Expand Down
Loading