Day 62 - pthread RWLock Internals and Fairness¶
Date¶
2026-05-28
Today's Goal¶
Learn reader-writer synchronization and understand how
pthread_rwlock works internally.
Focus areas:
- multiple-reader concurrency
- writer exclusivity
- rwlock fairness policy
- writer starvation
- mini rwlock implementation
What I Learned¶
pthread_rwlock semantics¶
pthread_rwlock allows:
- multiple concurrent readers
- one exclusive writer
Compared with mutex:
- mutex allows only one owner
- rwlock separates reader phase and writer phase
Reader preference vs writer preference¶
Implemented two fairness policies.
Reader preference¶
Readers may still acquire lock while writer is waiting.
Result:
- high reader throughput
- writer may wait for very long time
Observed writer wait time exceeding 40 seconds.
Writer preference¶
New readers blocked once writer enters waiting state.
Result:
- lower writer latency
- lower reader throughput
Important observation:
Mini rwlock implementation¶
Implemented a simplified spin rwlock using:
- atomic reader counter
- writer state machine
- CAS-based writer acquisition
Writer states:
Reader rollback mechanism¶
Implemented reader re-check logic to prevent:
Flow:
Futex observation¶
Used:
Observed:
- FUTEX_WAIT
- FUTEX_WAKE
- EAGAIN retry behavior
Confirmed rwlock slow path uses futex wait/wake operations.
Memory ordering¶
Started exploring:
- memory_order_acquire
- memory_order_release
Understanding memory visibility is important for synchronization correctness.
Completed Labs¶
- Lab1 multi-reader parallelism
- Lab2 writer waiting behavior
- Lab3 starvation observation
- Lab4 mini spin rwlock
- Lab5 futex trace observation
Next Step¶
Possible next topics:
- seqlock
- RCU
- futex-based rwlock
Planned next topic: