molecalculator

Moles & Molar Mass

Atomic Variables in C: A Complete Guide

Calculator No. 01-9474 · Updated · Formula and assumptions shown below

Molarity 0.2000 mol/L
Concentration in millimolar
200.00 mM
= Molarity × 1000
Mass of solute
2.922 g
Set in the form below
Molar mass
58.44 g/mol
Set in the form below
You enter
Mass of solute (g), Molar mass (g/mol), Final solution volume (mL)
You get
Molarity (mol/L), Concentration in millimolar (mM)
Rounding
4 dp · 2 dp

For study and lab planning. The result follows from the numbers you enter and the formula shown. Check it against your method before you weigh, mix or dilute anything, follow the safety data sheet and your supervisor, and do not use it for clinical, dosing or medication work.

Atomic variables in C are variables that can be read and modified by multiple threads without data races, using operations that are indivisible (atomic) at the hardware level. You declare them with the _Atomic qualifier (or stdatomic.h macros) and use dedicated functions like atomic_fetch_add to perform thread-safe updates. This guide explains how they work, when to use them, and the pitfalls to avoid.

Background: Why Atomic Variables Exist

In a multithreaded program, two threads can read and write the same memory location at the same time. Without synchronization, this is a data race—undefined behavior in C. The classic example is a shared counter: if two threads execute counter++ simultaneously, both may read the same old value, add 1, and write back, losing an increment. Atomic variables solve this by making each operation on the variable indivisible, so no thread can see a partial update. They are the building blocks for locks, reference counters, and lock-free data structures.

The C11 standard introduced _Atomic as a type qualifier and the <stdatomic.h> header with a set of macros and functions. Before C11, you had to use compiler-specific extensions (GCC’s __sync builtins) or platform APIs. Atomic operations are typically implemented using hardware instructions (e.g., x86 LOCK prefix, ARM LDREX/STREX), but the C standard abstracts this away.

How to Declare and Use Atomic Variables

You can declare an atomic variable in two equivalent ways:

  • _Atomic int counter; – using the qualifier directly.
  • atomic_int counter; – using the typedef from <stdatomic.h> (this is the same as _Atomic int).

Once declared, you can use the atomic operations from <stdatomic.h>:

  • atomic_init(&counter, 0) – initialize before any concurrent use.
  • atomic_load(&counter) – read the value atomically.
  • atomic_store(&counter, 42) – write a value atomically.
  • atomic_fetch_add(&counter, 1) – add 1 and return the old value.
  • atomic_fetch_sub(&counter, 1) – subtract 1 and return the old value.
  • atomic_exchange(&counter, 10) – set to 10 and return the old value.
  • atomic_compare_exchange_strong(&counter, &expected, 10) – if current equals expected, set to 10; otherwise update expected.

You can also use the +=, -=, ++, -- operators directly on atomic variables—they are atomic for most types. For example, counter++ is equivalent to atomic_fetch_add(&counter, 1).

Here is a minimal working example:

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

atomic_int counter = 0;

int increment(void *arg) {
    for (int i = 0; i < 100000; i++) {
        atomic_fetch_add(&counter, 1);
    }
    return 0;
}

int main(void) {
    thrd_t t1, t2;
    thrd_create(&t1, increment, NULL);
    thrd_create(&t2, increment, NULL);
    thrd_join(t1, NULL);
    thrd_join(t2, NULL);
    printf("Counter = %d\n", atomic_load(&counter)); // 200000
    return 0;
}

Note that atomic_int counter = 0; uses static initialization; for local variables, use atomic_init before any concurrent access.

Memory Order: The Key to Correctness

Atomic operations accept an optional memory order argument that controls how the compiler and CPU reorder operations. The default is memory_order_seq_cst (sequentially consistent), which is the safest but potentially slowest. The other orders are:

  • memory_order_relaxed – only guarantees atomicity, no ordering constraints. Fastest, but only useful for simple counters where you don’t need to order other operations.
  • memory_order_acquire – for load operations; prevents subsequent reads/writes from moving before the load.
  • memory_order_release – for store operations; prevents prior reads/writes from moving after the store.
  • memory_order_acq_rel – for read-modify-write operations; combines acquire and release.

Example: atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed).

Choosing the wrong memory order can lead to subtle bugs. For most applications, stick with the default seq_cst unless you have measured a performance problem and understand the C11 memory model deeply.

When to Use Atomic Variables (and When Not To)

Atomic variables are ideal for:

  • Simple counters (hits, statistics, reference counts).
  • Flags that signal a thread to stop (e.g., atomic_bool stop).
  • Implementing lock-free data structures (e.g., a lock-free stack using atomic_compare_exchange).
  • Sharing immutable data after a release/acquire handshake.

They are not suitable for:

  • Complex multi-step operations (e.g., updating two variables together). Use a mutex instead.
  • Large data structures (arrays, structs) – atomics only work on scalar types and pointers.
  • Situations where you need to block waiting for a condition – use condition variables.

If you need to protect a critical section that involves multiple variables, a mutex (mtx_t in C11 threads) is the right tool. Atomics are for simple, single-variable operations.

Common Mistakes and Pitfalls

Here are frequent errors when working with atomic variables:

  • Forgetting to initialize: Local atomics must be initialized with atomic_init before any thread uses them; otherwise, they contain garbage.
  • Using non-atomic operations: Reading or writing an atomic variable with plain = or read is not guaranteed to be atomic. Always use the atomic functions or operators.
  • Assuming all types are atomic: The standard only guarantees that atomic_flag is lock-free. Other atomic types may use internal locks if the hardware doesn’t support them. You can check with atomic_is_lock_free(&var).
  • Misusing memory order: Using memory_order_relaxed for a flag that guards a shared pointer can cause the pointer read to be reordered before the flag is set. Use acquire/release or seq_cst.
  • Data race on initialization: If two threads initialize the same atomic variable concurrently, that’s a data race. Initialize before creating threads.

Another misconception: atomic variables do not make your program thread-safe automatically. They only make individual operations atomic. If you have a sequence like “read value, modify, write back” using separate atomic calls, another thread can interleave between them. Use atomic_fetch_add or atomic_compare_exchange for read-modify-write operations.

Performance Costs and Lock-Free Guarantees

Atomic operations are not free. On modern CPUs, they often involve a lock prefix (x86) or exclusive access instructions (ARM), which can be 10–100 times slower than a plain operation. The cost increases with contention (many threads hitting the same variable). In practice, a single atomic counter update is still fast enough for most uses, but avoid putting atomics in tight loops if you don’t need them.

Whether an atomic type is lock-free (no internal mutex) depends on the hardware and compiler. The C standard only guarantees that atomic_flag is lock-free. You can query atomic_is_lock_free(&var) at runtime. For example, on x86-64, atomic_int is usually lock-free, but on some embedded platforms it may not be. If lock-free is critical, you may need to use _Atomic with a type that the platform supports.

Alternatives to Atomic Variables

If atomics are too low-level or don’t fit your problem, consider:

  • Mutexes (mtx_t): protect a critical section with multiple statements. Simple and correct, but can block and have overhead.
  • Condition variables: for signaling between threads while holding a mutex.
  • Thread-local storage (_Thread_local): if each thread only needs its own copy, avoid sharing entirely.
  • Read-write locks (not in C11 standard, but available via POSIX pthread_rwlock_t): allow multiple readers, one writer.
  • Lock-free data structures: built on atomics, but complex to implement correctly. Use a well-tested library if possible.

For most applications, a mutex is easier to reason about than a carefully crafted atomic algorithm. Use atomics when you need maximum performance for a simple operation, or when you’re building a lock-free structure.

Frequently Asked Questions

Are atomic variables the same as volatile?

No. volatile tells the compiler not to optimize away reads/writes, but it does not make operations atomic or prevent data races. Atomic variables are the correct tool for multithreading; volatile is for memory-mapped I/O and signal handlers.

Can I use atomic_int with printf?

No, you need to load it first: printf("%d\n", atomic_load(&counter));. Passing an atomic variable directly to a variadic function is undefined behavior because the type may be different.

What is the difference between atomic_fetch_add and atomic_add_fetch?

atomic_fetch_add returns the old value, while atomic_add_fetch returns the new value. Both perform the addition atomically. For example, if counter is 5, atomic_fetch_add(&counter, 1) returns 5 and sets it to 6; atomic_add_fetch(&counter, 1) returns 6.

Is atomic_flag the same as a boolean?

Not exactly. atomic_flag is a minimal atomic type that only supports atomic_flag_test_and_set and atomic_flag_clear. It is guaranteed to be lock-free, making it useful for spinlocks. For a boolean flag, use atomic_bool, which supports all atomic operations.

Do atomic variables work across processes?

No, C11 atomics are for threads within a single process. For inter-process synchronization, you need OS-specific mechanisms like POSIX shared memory with mutexes or semaphores.

Why is my atomic counter still not correct?

If you’re using atomic_fetch_add correctly, the counter should be correct. Common issues include: not all threads use the atomic operation (one uses counter++ directly), or you’re reading the value with a plain assignment while another thread writes. Also ensure you join all threads before reading the final value.

Assumptions

This guide assumes a C11-compliant compiler with <stdatomic.h> support, and a target platform that provides atomic instructions for the types you use. The behavior of memory orders is as defined by the C11 standard; actual hardware may have additional subtleties. For lock-free guarantees, always check atomic_is_lock_free on your target.

Related

Formula used
in m | Mass of solute | g | 2.922 | 0
in mm | Molar mass | g/mol | 58.44 | 0.001
in v | Final solution volume | mL | 250 | 0.001
out c | Molarity | mol/L | m / mm / (v / 1000) | 4
out cmm | Concentration in millimolar | mM | c * 1000 | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation with the constants and conversion factors written on the page, rounded as each result states. See method and constants, the disclaimer or report an error.

More in this section

The whole Moles & Molar Mass section →