YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Correctness & careChapter 65 of 73

Threads, atomics, and shared state

Reason about data races, atomic updates, mutex invariants, release/acquire publication, and thread lifetime.

7 min readAdvancedC17 baseline
Offline reading
In this chapter8 sections

Two threads can work on overlapping timelines and access shared information. They need agreed rules for who may access it and when. We will separate data races, atomic operations, mutex protection, and the ordering used to publish data.

1. Data races are about conflicting unordered accesses

A data race involves conflicting actions in different threads, at least one non-atomic, without the required happens-before ordering. A conflicting pair accesses the same memory location and at least one modifies it. A data race has undefined behavior. Concurrent reads alone are not a race; using a single CPU, sleeping briefly, or declaring an object volatile does not supply synchronization.

A happens-before relation combines specified within-thread sequencing and inter-thread synchronization. It is a language relation, not merely wall-clock observation. Thread creation, successful joining, mutex operations, and correctly paired atomic operations can establish ordering. Thread-local state has separate objects per thread, but it does not make other shared objects safe.

2. Individual atomic operations are not whole transactions

Complete C17 program
#include <assert.h>
#include <stdatomic.h>

int main(void)
{
    atomic_int counter;
    atomic_init(&counter, 0);
    int first_read = atomic_load(&counter);
    int second_read = atomic_load(&counter);
    atomic_store(&counter, first_read + 1);
    atomic_store(&counter, second_read + 1);
    int result = atomic_load(&counter);
    assert(result == 1);
    return 0;
}

This single-threaded model deliberately interleaves the steps of two imagined updates: both read zero, then both store one. Every access is atomic and the final value is one. A real load-plus-store update is not one indivisible increment. Use an appropriate atomic read-modify-write operation or protect the multi-step invariant with a mutex.

Complete C17 program
#include <assert.h>
#include <stdatomic.h>
#include <stdlib.h>
#include <threads.h>

#if defined(__STDC_NO_THREADS__) || defined(__STDC_NO_ATOMICS__)
#error "This example requires C threads and atomics"
#endif

static atomic_uint counter;

static int increment(void *unused)
{
    (void)unused;
    for (unsigned i = 0; i < 1000; ++i) {
        atomic_fetch_add_explicit(&counter, 1U, memory_order_relaxed);
    }
    return 0;
}

int main(void)
{
    atomic_init(&counter, 0U);
    thrd_t worker;
    if (thrd_create(&worker, increment, NULL) != thrd_success) return EXIT_FAILURE;
    (void)increment(NULL);
    int worker_result = 0;
    if (thrd_join(worker, &worker_result) != thrd_success) _Exit(EXIT_FAILURE);
    if (worker_result != 0) return EXIT_FAILURE;
    unsigned total = atomic_load_explicit(&counter, memory_order_relaxed);
    assert(total == 2000U);
    return EXIT_SUCCESS;
}

The worker and main each add one thousand times. Atomic fetch-add preserves each update, and two thousand fits every standard unsigned int. Relaxed ordering is sufficient for this isolated counter: it supplies atomicity without publishing unrelated data. The successful join establishes completion before the final check. GCC checks here link the hosted thread examples with -pthread; build flags are platform conventions.

3. A mutex can protect a larger invariant

A mutex gives mutually exclusive access when all participating accesses obey the lock discipline. The following version protects a non-atomic counter. Its final read happens after joining the worker, when no thread still modifies that counter. Holding one lock does not protect data accessed elsewhere without the same discipline, and multiple locks require a consistent ordering to avoid deadlock.

Read the mutex counter
Complete C17 program
#include <assert.h>
#include <stdlib.h>
#include <threads.h>

#if defined(__STDC_NO_THREADS__)
#error "This example requires C threads"
#endif

static mtx_t gate;
static unsigned counter;

static int increment(void *unused)
{
    (void)unused;
    for (unsigned i = 0; i < 1000; ++i) {
        if (mtx_lock(&gate) != thrd_success) _Exit(EXIT_FAILURE);
        ++counter;
        if (mtx_unlock(&gate) != thrd_success) _Exit(EXIT_FAILURE);
    }
    return 0;
}

int main(void)
{
    if (mtx_init(&gate, mtx_plain) != thrd_success) return EXIT_FAILURE;
    thrd_t worker;
    if (thrd_create(&worker, increment, NULL) != thrd_success) {
        mtx_destroy(&gate);
        return EXIT_FAILURE;
    }
    (void)increment(NULL);
    int worker_result = 0;
    if (thrd_join(worker, &worker_result) != thrd_success) _Exit(EXIT_FAILURE);
    mtx_destroy(&gate);
    if (worker_result != 0) return EXIT_FAILURE;
    assert(counter == 2000U);
    return EXIT_SUCCESS;
}

These bounded examples check creation and synchronization results. A join failure leaves completion uncertain, so they use _Exit for that unrecoverable path instead of destroying resources and continuing under a guessed lifetime. Mutex lock/unlock failures use the same emergency policy. _Exit bypasses normal cleanup; production interfaces need an explicit failure policy rather than assuming recovery is always possible.

4. Publishing data needs the matching ordering relation

A release store can synchronize with an acquire load that reads its value under the relevant atomic rule. In this one-shot example, payload is written before the release; the consumer reads payload only after observing true through acquire. No later write modifies payload. Replacing this with a relaxed flag would not provide that publication relation.

One-shot publication
Producer
Write payload, then release-store ready
Consumer
Acquire-load true, then read payload
The acquire must observe the relevant release; a similarly named flag or elapsed time is not enough.
Read the publication example
Complete C17 program
#include <stdatomic.h>
#include <stdbool.h>
#include <stdlib.h>
#include <threads.h>

#if defined(__STDC_NO_THREADS__) || defined(__STDC_NO_ATOMICS__)
#error "This example requires C threads and atomics"
#endif

static int payload;
static atomic_bool ready;

static int consume(void *unused)
{
    (void)unused;
    while (!atomic_load_explicit(&ready, memory_order_acquire)) thrd_yield();
    return payload == 42 ? 0 : 1;
}

int main(void)
{
    atomic_init(&ready, false);
    thrd_t worker;
    if (thrd_create(&worker, consume, NULL) != thrd_success) return EXIT_FAILURE;
    payload = 42;
    atomic_store_explicit(&ready, true, memory_order_release);
    int result = 1;
    if (thrd_join(worker, &result) != thrd_success) _Exit(EXIT_FAILURE);
    return result == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

The polling loop is a small model, not a guarantee of fairness or a recommendation for production waiting. thrd_yield is a scheduling hint; C does not promise a particular completion time. Condition variables or other documented waiting facilities are usually better for a real waiting policy, and their predicate must be checked under the synchronization contract.

5. Availability, lock freedom, and correctness differ

Thread and atomic support remain conditional in C17 and C23, with the corresponding __STDC_NO_THREADS__ and __STDC_NO_ATOMICS__ feature macros. Check the target implementation. An atomic type need not be lock-free: atomic_is_lock_free queries the property, while the matching ATOMIC_*_LOCK_FREE macros describe the implementation’s guarantees. Sequentially consistent defaults simplify ordering, but do not automatically fix a larger algorithm’s logic or lifetime.

Primary references and further reading

Before you move on

  • Shared mutable state needs the required access and ordering rules.
  • Atomic operations do not automatically make a larger multi-step update a transaction.
  • Synchronization, resource lifetimes, and API support must all fit the design.
Keep these ideas separate
volatile / Synchronization
volatile access is not a substitute for atomic or locking rules that establish valid inter-thread communication.
Explain it in your own words

Why does publishing a flag need an ordering agreement for the ordinary data associated with it?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

Does volatile alone make conflicting shared accesses safe between C threads?
Read the explanation for every choice
  1. Yes, volatile is a thread lock.

    volatile is not a mutex and does not by itself provide atomicity or synchronization.

  2. No. A suitable synchronization or atomic-access design is still needed.

    ✓ Correct reasoning. Conflicting unsynchronized non-atomic accesses can form a data race.

  3. Every access becomes an indivisible operation.

    volatile does not generally turn ordinary operations into atomic operations.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.

Standardized threading arrived comparatively late to C, with the C11 standard:

  • <threads.h> provides thrd_create/thrd_join for spawning and waiting on threads, mtx_t mutexes for mutual exclusion, and condition variables for signaling between threads. Support is optional — an implementation lacking it can indicate as much by defining __STDC_NO_THREADS__ — and in practice, many platforms still rely instead on POSIX threads (pthreads), which predate C11's native threading support and remain more widely available.
  • <stdatomic.h> provides atomic types (such as atomic_int) and operations guaranteed not to be subject to data races, along with explicit memory-ordering controls for programmers who need fine-grained control over how operations become visible across threads. Like threading, atomic support is technically optional (__STDC_NO_ATOMICS__).
  • _Thread_local (Section 15) gives each thread its own independent copy of a variable — useful for per-thread state such as a thread-local errno.

C11 introduced a memory model that defines inter-thread ordering and data races. A data race involves conflicting actions in different threads (at least one modifies an object), at least one non-atomic access, and no required happens-before ordering; a data race is undefined behavior. Concurrent reads alone are not a data race. Mutexes, correctly used atomics, and thread creation/join ordering can establish the needed ordering. An atomic object does not automatically make an entire multi-step algorithm atomic, and volatile is not a replacement for synchronization.

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 65 / 73

In this chapter

Threads, atomics, and shared state

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping