bhylu.com

Advertisements

C volatile and Atomics

Use a C11 atomic counter for indivisible updates and explain what relaxed ordering does not promise.

How it works

volatile tells an implementation that accesses have observable significance according to its documented rules. It does not make a shared counter atomic or prevent data races between threads. stdatomic.h supplies atomic types and operations when supported. This example demonstrates their API in one thread; it does not claim to exercise a scheduler or prove a concurrent algorithm. A relaxed increment is suitable for a standalone count when no other data publication depends on its ordering. Real shared structures often need a stronger synchronization design.

Run it locally

Use a hosted C17 compiler in a separate lab folder. The command assumes a driver named cc; substitute gcc, clang or zig cc as appropriate. C does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed for these C programs.

cc -std=c17 -Wall -Wextra -Wpedantic -Werror volatile-atomics.c -o lesson

On Windows, use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Math-library linking differs by toolchain; GCC on many Unix systems needs -lm after the source.

Environment boundary: Requires a C17 implementation with stdatomic.h support. This listing is a single-thread atomic API demonstration, not a multithread stress test.

Download the complete C source. File-writing labs must run in an empty private directory, away from existing reports.

Example

C17 · volatile-atomics.c

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

int main(void) {
    atomic_uint count;
    atomic_init(&count, 0u);
    atomic_fetch_add_explicit(&count, 2u, memory_order_relaxed);
    atomic_fetch_add_explicit(&count, 1u, memory_order_relaxed);
    printf("Atomic count: %u\n", atomic_load_explicit(&count, memory_order_relaxed));
    return 0;
}

Expected result

Atomic count: 3

Both increments update the same atomic object and the load reads its final value. Atomic support and lock-free properties depend on implementation and type; atomics may use locks internally. In a multithreaded program every conflicting access needs a valid synchronization contract. Optional threads.h support should be checked before attempting a C library thread lab.

For language and library rules, consult the WG14 C working group and its public C11 committee draft, which describes the core facilities used here; C17 incorporates corrections. Check your compiler and runtime documentation for implementation details.

Advertisements