Skip to content

Day60 — Atomics and Memory Ordering

Objectives

Understand synchronization behavior through experiments.


Lab1

Race condition.

Experiment

Two threads:

counter++

Observe inconsistent result.


Lab2

Atomic counter.

APIs

atomic_fetch_add()

Compare correctness.


Lab3

Spin lock.

APIs

atomic_compare_exchange_strong()

Implement:

my_spin_lock()

my_spin_unlock()

Observe:

  • CPU usage
  • contention

Lab4

Memory ordering.

Producer

data=i

store_release(ready)

Consumer

load_acquire(ready)

read(data)

Observe visibility guarantees.


Validation

Expected:

wrong_count=0

  • atomics-memory-ordering
  • synchronization-primitives-selection

  • c11-atomics