Skip to content

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:

Whether waiting writers block new readers
defines rwlock fairness policy.

Mini rwlock implementation

Implemented a simplified spin rwlock using:

  • atomic reader counter
  • writer state machine
  • CAS-based writer acquisition

Writer states:

WRITER_FREE
WRITER_WAIT_QUEUE
WRITER_ACQUIRED

Reader rollback mechanism

Implemented reader re-check logic to prevent:

reader and writer entering critical section simultaneously

Flow:

reader_count++
re-check writer state
rollback if writer acquired concurrently

Futex observation

Used:

strace -f -e futex ./rwlock_demo

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:

Day63 - Seqlock and RCU Motivation