Skip to content

Commit faa9279

Browse files
committed
Add some comments to futex rwlock impl.
1 parent 6b2344b commit faa9279

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

library/std/src/sys/unix/locks/futex_rwlock.rs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,31 +75,36 @@ impl RwLock {
7575

7676
#[inline]
7777
pub unsafe fn write(&self) {
78-
if let Err(s) = self
79-
.state
80-
.fetch_update(Acquire, Relaxed, |s| (readers(s) == 0).then(|| s + WRITE_LOCKED))
81-
{
82-
self.write_contended(s);
78+
if !self.try_write() {
79+
self.write_contended();
8380
}
8481
}
8582

8683
#[inline]
8784
pub unsafe fn read_unlock(&self) {
88-
if self.state.fetch_sub(READ_LOCKED, Release) == READ_LOCKED + WRITERS_WAITING {
85+
let s = self.state.fetch_sub(READ_LOCKED, Release);
86+
87+
// It's impossible for readers to be waiting if it was read locked.
88+
debug_assert!(!readers_waiting(s));
89+
90+
// Wake up a writer if we were the last reader and there's a writer waiting.
91+
if s == READ_LOCKED + WRITERS_WAITING {
8992
self.wake_after_read_unlock();
9093
}
9194
}
9295

9396
#[inline]
9497
pub unsafe fn write_unlock(&self) {
9598
if let Err(e) = self.state.compare_exchange(WRITE_LOCKED, 0, Release, Relaxed) {
99+
// Readers or writers (or both) are waiting.
96100
self.write_unlock_contended(e);
97101
}
98102
}
99103

100104
#[cold]
101105
fn read_contended(&self, mut state: i32) {
102106
loop {
107+
// If we can lock it, lock it.
103108
if read_lockable(state) {
104109
match self.state.compare_exchange(state, state + READ_LOCKED, Acquire, Relaxed) {
105110
Ok(_) => return, // Locked!
@@ -110,6 +115,7 @@ impl RwLock {
110115
}
111116
}
112117

118+
// Check for overflow.
113119
if readers(state) == MAX_READERS {
114120
panic!("too many active read locks on RwLock");
115121
}

0 commit comments

Comments
 (0)