Skip to content

Do not treat re-entrant read holds as other readers - #1135

Open
adityawrk wants to merge 1 commit into
ruby-concurrency:masterfrom
adityawrk:fix/read-write-lock-reentrancy
Open

adityawrk wants to merge 1 commit into
ruby-concurrency:masterfrom
adityawrk:fix/read-write-lock-reentrancy

Conversation

@adityawrk

@adityawrk adityawrk commented Nov 29, 2026 •

Copy link
Copy Markdown

Problem

ReentrantReadWriteLock counts reader threads in the shared counter and counts re-entrant acquisitions in the per-thread hold count. The write-lock checks compared those two numbers.

A thread that acquired its read lock twice, while one other thread also held a read lock, saw both numbers equal 2 and was granted the write lock. try_write_lock returned true. On current master, before this change:

[:first, false]
[:second, true]

acquire_write_lock waits for the same comparison. release_read_lock signaled a waiting writer only when the reader count hit 0. An upgrading thread still holds its own read lock, so the count stops at 1 and the upgrader is never woken. Later readers and writers then block behind it.

Fix

A thread holds every current read lock only when it is the sole reader: the reader count is 1 if this thread holds a read lock, and 0 if it does not. Re-entrant acquisitions no longer count as other readers.

Releasing a read lock also signals a waiting writer when one reader remains, so an upgrading writer is woken once the other reader lets go. A writer that holds no read lock wakes, sees the remaining reader, and waits again; the last release still signals it.

After the change the same script prints false both times, and once the other reader releases the upgrade succeeds. A blocked upgrade now finishes, and a new reader can acquire the lock afterward:

[:first, false]
[:second, false]
[:after, true]
upgrade=true
reader=true

spec/concurrent/atomic/reentrant_read_write_lock_spec.rb: 34 examples, 0 failures.

Fixes #1129
Fixes #1130

…#1129)

The lock counter counts reader threads, while the per-thread count
counts acquisitions. Comparing the two granted a write lock to a thread
that had re-entered its own read lock while another thread still held
one, and the other thread's release never woke the upgrading writer.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant