Atomic objects

suggest change

C11 introduced atomic types and operations in <stdatomic.h>. They allow threads to coordinate access to shared state without creating a data race.

#include <stdatomic.h>

static atomic_uint completed = 0;

void mark_complete(void)
{
    atomic_fetch_add(&completed, 1);
}

A data race requires conflicting accesses to the same memory location from different threads, at least one of which is a write, without suitable atomic operations or synchronization. Concurrent reads alone do not form a data race.

Atomic operations are indivisible with respect to other atomic accesses to the same object. They also have a memory order. The default sequentially consistent order is the easiest to reason about; weaker orders can improve performance in specialized algorithms but require a precise proof.

unsigned count = atomic_load(&completed);

Most scalar types can be written using the _Atomic qualifier or a typedef such as atomic_uint. Atomic structure types are possible, but an implementation may use locks internally. Use atomic_is_lock_free when lock freedom is a requirement.

atomic_flag is guaranteed to be lock-free. Other atomic types may or may not be lock-free on a particular implementation.

Do not mix atomic and non-atomic access to the same object while threads can access it concurrently. Also remember that making individual fields atomic does not automatically preserve an invariant involving several fields; a mutex is often the clearer solution.

Atomics are optional in C11 and later; implementations that omit them define __STDC_NO_ATOMICS__. Check the target implementation when supporting such environments.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents