C stdatomic.h Header

Beginner
6 min read
Updated: Nov 2026
3 examples
C11

What Is stdatomic.h?

<stdatomic.h> is the C11 header for atomic operations: reads and writes that other threads see as one indivisible step. It defines types such as atomic_int and operations such as atomic_fetch_add.

Atomics let threads share counters, flags, and pointers without a mutex. Each operation also takes a memory order that controls how surrounding reads and writes are ordered; the plain forms use sequentially consistent ordering, the safest default. Support is optional: an implementation without atomics defines __STDC_NO_ATOMICS__.

Remember
#include <stdatomic.h>

atomic_int counter = 0;

atomic_store(&counter, 5);
int v   = atomic_load(&counter);
int old = atomic_fetch_add(&counter, 1);   /* returns the old value */

atomic_compare_exchange_strong(&obj, &expected, desired);

atomic_flag f = ATOMIC_FLAG_INIT;
atomic_flag_test_and_set(&f);
UsePrefer
Shared counteratomic_int + atomic_fetch_add
Stop flag between threadsatomic_bool with atomic_load / atomic_store
Lock-free updateatomic_compare_exchange_strong
Simple spin lockatomic_flag

How to Use stdatomic.h in C

Declare an atomic type, then use the named operations through its address.

  1. Add #include <stdatomic.h> and compile with -std=c11.
  2. Declare an atomic object such as atomic_int, atomic_bool, or _Atomic(T).
  3. Use atomic_load, atomic_store, and atomic_fetch_* with the object's address.
  4. Stay with the default sequentially consistent order until you have a reason to relax it.
  5. Add -pthread when the atomics are shared by threads.
PieceRequired?Role
#include <stdatomic.h>YesDeclares atomic types and functions
Atomic typeYesatomic_int or _Atomic(T)
-pthreadWith threadsNeeded on some systems when threads share the data

Pseudocode

Pseudocode
atomic_int counter = 0
old = atomic_fetch_add(&counter, 5)     // old = 0, counter = 5
v   = atomic_load(&counter)             // 5

ok = atomic_compare_exchange_strong(&x, &expected, desired)
  if x == expected: x = desired, ok = true
  else:             expected = x, ok = false

Cheat Sheet

Common names in stdatomic.h.

NameMeaning
atomic_int, atomic_bool, atomic_size_tAtomic versions of common types
_Atomic(T)Atomic version of any suitable type T
atomic_load, atomic_storeAtomic read and write
atomic_fetch_add, _sub, _or, _and, _xorRead-modify-write; return the old value
atomic_exchangeStore a new value and return the old one
atomic_compare_exchange_strong / _weakConditional swap
atomic_flag_test_and_set, atomic_flag_clearLock-free boolean flag
memory_order_relaxed … memory_order_seq_cstOrdering constraints
atomic_thread_fenceStand-alone memory fence

Worked Walkthrough — Fetch-Add and Compare-Exchange

Follow a counter through two updates and one conditional swap.

Calculation
atomic_int counter = 0;

atomic_fetch_add(&counter, 5)  -> returns 0, counter becomes 5
atomic_fetch_sub(&counter, 2)  -> returns 5, counter becomes 3
atomic_load(&counter)          -> 3

value = 10, expected = 10, desired = 20
compare_exchange: value == expected -> value = 20, returns true

value = 20, expected = 10, desired = 30
compare_exchange: value != expected -> expected = 20, returns false

C Examples

Compile with gcc file.c -std=c11 -o out (add -pthread if the link fails).

Example 1 — Update a Counter with atomic_fetch_add

Add to an atomic counter and read the old and new values.

C
#include <stdatomic.h>
#include <stdio.h>

int main(void) {
    atomic_int counter = 0;
    int old = atomic_fetch_add(&counter, 5);

    printf("old = %d\n", old);
    printf("new = %d\n", atomic_load(&counter));
    return 0;
}

How It Works

  1. Declare an atomic. atomic_int is an int with atomic operations.
  2. Fetch-add returns the old value. The counter was 0 before the add.
  3. Read with atomic_load. The new value is 5.

Example 2 — Conditional Update with compare-exchange

Swap a value only when it still holds what you expect.

C
#include <stdatomic.h>
#include <stdio.h>

int main(void) {
    atomic_int value = 10;
    int expected = 10;

    if (atomic_compare_exchange_strong(&value, &expected, 20)) {
        printf("swapped, value = %d\n", atomic_load(&value));
    }

    expected = 10;
    if (!atomic_compare_exchange_strong(&value, &expected, 30)) {
        printf("failed, expected updated to %d\n", expected);
    }
    return 0;
}

How It Works

  1. First call succeeds. value equals expected (10), so it becomes 20.
  2. Second call fails. value is now 20, not the expected 10.
  3. Failure refreshes expected. On failure the current value is written into expected, ready for a retry loop.

Example 3 — Use atomic_flag as a Lock Flag

Test-and-set a flag and clear it again.

C
#include <stdatomic.h>
#include <stdio.h>

int main(void) {
    atomic_flag lock = ATOMIC_FLAG_INIT;

    printf("first:  %d\n", atomic_flag_test_and_set(&lock));
    printf("second: %d\n", atomic_flag_test_and_set(&lock));

    atomic_flag_clear(&lock);
    printf("after clear: %d\n", atomic_flag_test_and_set(&lock));
    return 0;
}

How It Works

  1. Start clear. ATOMIC_FLAG_INIT begins the flag in the clear state.
  2. Test-and-set returns the old state. The first call returns 0 (was clear), the second returns 1 (already set).
  3. Clear to release. After atomic_flag_clear the next test-and-set returns 0 again.

Edge Cases & Pitfalls

Atomics are easy to misuse when you step outside the simple patterns.

init

Initialize before sharing

Use an initializer or atomic_init() before other threads can see the object. Initialization itself is not atomic.

cast

Do not cast away _Atomic

Accessing an atomic object through a non-atomic pointer is a data race.

order

Prefer the default order

memory_order_relaxed is fast but easy to get wrong. Start with the default sequentially consistent order.

support

Support is optional

If __STDC_NO_ATOMICS__ is defined, the implementation does not provide the header.

Performance & Portability Notes

ApproachCostBest for
atomic_fetch_addA single hardware instruction on most CPUsCounters and statistics
Compare-exchange loopMay retry under contentionLock-free data structures
atomic_flag spin lockBurns CPU while waitingVery short critical sections

Atomic operations avoid the cost of a mutex for simple shared values, but heavy contention on one variable still slows threads down.

Key Takeaways

  • Role: indivisible reads and writes for shared data.
  • Pattern: declare atomic_int, then use atomic_load, atomic_store, and atomic_fetch_*.
  • Default order: sequentially consistent unless you ask otherwise.
  • Pair with threads: see threads.h.

One line: stdatomic.h lets threads share simple values safely without taking a lock.

Frequently Asked Questions

stdatomic.h is the C11 header for atomic types and operations such as atomic_int, atomic_load, atomic_store, and atomic_fetch_add.
It adds to the atomic object and returns the value the object held before the addition.
It updates a value only if it still equals an expected value, which is the building block of lock-free algorithms. On failure the current value is copied into expected.
For one shared counter or flag, atomics are enough. For protecting several variables that must change together, use a mutex from threads.h.
It controls how reads and writes around an atomic operation can be reordered. The default, memory_order_seq_cst, is the strongest and safest.
It is optional in C11. Check that __STDC_NO_ATOMICS__ is not defined. GCC, Clang, and recent MSVC provide it.

Next: stdbool.h

Use bool, true, and false for readable conditions.

stdbool.h tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful