CodeBlanks Logo Icon CodeBlanks

Atomics

Learn atomic operations with stdatomic.h.

stdatomic.h atomic operations

The stdatomic.h header provides atomic operations introduced in C11. The atomic_int type offers indivisible increment and decrement. atomic_fetch_add(&counter, 1) atomically increments the counter.

Atomic operations are critical for thread safety. A plain counter++ is three machine instructions (load, add, store); two threads doing it at once can lose an increment. atomic_fetch_add is a single indivisible instruction, preventing such data races. Memory ordering is also controlled in this header; memory_order_relaxed is the weakest, memory_order_seq_cst the strongest.

Memory ordering

The behavior of atomic operations is controlled by memory ordering. The default memory_order_seq_cst is the strongest and safest; all threads see the same order.

memory_order_relaxed is the weakest; only atomicity is guaranteed, not ordering. It is used for performance but requires care. You can specify it explicitly with atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed). In most cases the default ordering suffices; weaker ordering is used only after profiling.

Practice Write an atomic counter

Add #include <stdatomic.h>. In int main(void) declare atomic_int counter = 0;. Call atomic_fetch_add(&counter, 1) twice. Print the result with printf("%d\n", counter).

Starter code

main.c
#include <stdio.h>
#include <stdatomic.h>

// atomik sayaç tanımla
// iki kez artır
// sonucu yazdır

Sample solution

main.c
#include <stdio.h>
#include <stdatomic.h>

int main(void) {
    atomic_int counter = 0;
    atomic_fetch_add(&counter, 1);
    atomic_fetch_add(&counter, 1);
    printf("%d\n", counter);
    return 0;
}

Expected output

2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which header provides atomic operations?

  • <atomic.h>
  • <sync.h>
  • <thread.h>
  • <stdatomic.h> Correct answer

Explanation: The stdatomic.h header holds C11 atomic operations.

2 Complete the atomic_fetch_add call

Question
atomic_int counter = 0;
atomic_fetch_add(&counter, ____);
Answer
atomic_int counter = 0;
atomic_fetch_add(&counter, 1);

Explanation: atomic_fetch_add(&counter, 1) increments the counter by one.

3 Match the atomic function

Term Meaning
atomic_fetch_add Atomic increment
atomic_fetch_sub Atomic decrement
atomic_load Atomic read
atomic_store Atomic write

All lessons in Expert