Skip to content

Day60 - Atomics / Memory Ordering / Futex Foundation

Date

2026-05-26


Goals

Learn synchronization foundations in Linux userspace.

Topics:

  • race condition
  • C11 atomics
  • compare-and-swap
  • memory ordering
  • futex concept
  • synchronization primitive selection

Completed

Lab1 — Race Condition

Implemented shared counter without synchronization.

Result:

Expected:

2000000

Observed:

counter=1199812

Finding:

counter++


load


modify


store

Operation is not atomic.


Lab2 — Atomic Counter

Replaced shared integer with:

atomic_uint
atomic_fetch_add()

Result:

counter=2000000

Finding:

Atomic operation guarantees correctness.


Lab3 — CAS Spin Lock

Implemented custom spin lock using:

atomic_compare_exchange_strong()

Protected:

counter++

Result:

counter=2000000

Observation:

CPU contention became noticeable.

Learned:

  • busy wait
  • cache contention
  • lock overhead

Lab4 — Memory Ordering

Implemented producer / consumer synchronization.

Version 1:

bool ready

Version 2:

atomic_load_explicit()

atomic_store_explicit()

memory_order_acquire

memory_order_release

Result:

wrong_count=0

Learned:

Visibility and ordering are independent from atomicity.


Key Takeaways

Synchronization hierarchy:

READ_ONCE


atomic


CAS


futex


mutex


condition variable

Next

Day61:

  • pthread mutex internals
  • futex wait/wake
  • condition variable internals