From c4a4f48c527453ddce2a2f1496473319290c6d8e Mon Sep 17 00:00:00 2001 From: Mara Bos Date: Mon, 11 Apr 2022 14:29:32 +0200 Subject: [PATCH] Use compare_exchange_weak in futex rwlock implementation. --- library/std/src/sys/unix/locks/futex_rwlock.rs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/library/std/src/sys/unix/locks/futex_rwlock.rs b/library/std/src/sys/unix/locks/futex_rwlock.rs index f602479bb52..2862cdea7da 100644 --- a/library/std/src/sys/unix/locks/futex_rwlock.rs +++ b/library/std/src/sys/unix/locks/futex_rwlock.rs @@ -75,7 +75,13 @@ pub unsafe fn try_read(&self) -> bool { #[inline] pub unsafe fn read(&self) { - if !self.try_read() { + let state = self.state.load(Relaxed); + if !read_lockable(state) + || self + .state + .compare_exchange_weak(state, state + READ_LOCKED, Acquire, Relaxed) + .is_err() + { self.read_contended(); } } @@ -101,7 +107,8 @@ fn read_contended(&self) { loop { // If we can lock it, lock it. if read_lockable(state) { - match self.state.compare_exchange(state, state + READ_LOCKED, Acquire, Relaxed) { + match self.state.compare_exchange_weak(state, state + READ_LOCKED, Acquire, Relaxed) + { Ok(_) => return, // Locked! Err(s) => { state = s; @@ -140,7 +147,7 @@ pub unsafe fn try_write(&self) -> bool { #[inline] pub unsafe fn write(&self) { - if !self.try_write() { + if self.state.compare_exchange_weak(0, WRITE_LOCKED, Acquire, Relaxed).is_err() { self.write_contended(); } } @@ -165,7 +172,7 @@ fn write_contended(&self) { loop { // If it's unlocked, we try to lock it. if unlocked(state) { - match self.state.compare_exchange( + match self.state.compare_exchange_weak( state, state | WRITE_LOCKED | other_writers_waiting, Acquire,