Compare two orders for the same atomic operation
Four threads each add one thirty thousand times to a shared counter using GCC atomic builtins. Run relaxed and sequentially consistent variants and check that both finish at one hundred twenty thousand. Do not add an unsynchronized non-atomic C counter as a supposedly valid baseline: a data race would make its observed result an invalid foundation for reasoning. The environment needs compatible GCC atomic builtins, pthreads and a monotonic clock. Save the program as counter.c and compile with cc -std=c11 -O2 -Wall -Wextra -Werror -pthread. This is a small process-local correctness and observation experiment, not a request to load a production service.
Wait for completion before checking the count
Each atomic read-modify-write increments the counter without the lost-update pattern of separate unsynchronized reads and writes. Relaxed ordering still supplies atomicity for this operation. The main thread joins all workers before checking the final count, so an intermediate value is not mislabeled as a completed result. The program also checks thread creation and join outcomes. Between variants, reset the counter only after every earlier worker has finished. Do not mix an unsynchronized reset into an active counting phase. Correct operation-level atomicity and well-defined lifecycle synchronization are both needed to interpret the assertion meaningfully; selecting a memory-order constant alone does not define the entire program contract.
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>
static unsigned long counter;
struct job { int order; };
static void *work(void *arg) {
const struct job *job = arg;
if (job->order == __ATOMIC_RELAXED) {
for (unsigned i = 0; i < 30000; ++i)
__atomic_fetch_add(&counter, 1UL, __ATOMIC_RELAXED);
} else {
for (unsigned i = 0; i < 30000; ++i)
__atomic_fetch_add(&counter, 1UL, __ATOMIC_SEQ_CST);
}
return NULL;
}
static void run(int order, const char *name) {
pthread_t threads[4]; struct job job = {order};
struct timespec a, b;
__atomic_store_n(&counter, 0UL, __ATOMIC_RELAXED);
assert(clock_gettime(CLOCK_MONOTONIC, &a) == 0);
for (unsigned i = 0; i < 4; ++i)
assert(pthread_create(&threads[i], NULL, work, &job) == 0);
for (unsigned i = 0; i < 4; ++i)
assert(pthread_join(threads[i], NULL) == 0);
assert(clock_gettime(CLOCK_MONOTONIC, &b) == 0);
unsigned long count = __atomic_load_n(&counter, __ATOMIC_RELAXED);
assert(count == 120000UL);
double seconds = (b.tv_sec - a.tv_sec) + (b.tv_nsec - a.tv_nsec) / 1e9;
printf("%s count=%lu seconds=%.6f\n", name, count, seconds);
}
int main(void) {
run(__ATOMIC_RELAXED, "relaxed");
run(__ATOMIC_SEQ_CST, "seq_cst");
return 0;
}Do not infer a publication protocol from counter success
The counter is the only shared data whose contents this experiment checks. It does not test a protocol that writes an ordinary array, increments a counter and lets another thread read the array after observing that increment. A correct relaxed final count does not establish visibility or race freedom for that different protocol. Publication may require matching release/acquire synchronization as well as a valid object lifetime and rules for later mutation. Conversely, choosing seq_cst does not repair every unrelated data race or use-after-free. Identify the required ordering relationship for each shared state. A test of one atomic quantity cannot silently become a proof about the ordering of all memory operations in a larger application.
A small timing difference is not surprising
All workers modify the same location, making cache-line ownership contention an important part of the workload. Some targets can generate similar or identical instruction sequences for these two variants. Relaxed ordering therefore does not promise a dramatic speedup. The reported interval includes worker creation and joining, not only increment instructions. A deeper comparison can investigate iteration counts, CPU placement, background load and generated instructions while preserving a clearly defined measurement boundary. First establish whether weaker ordering is valid for the application’s contract. Do not change production synchronization based on a favorable single short run without checking which guarantees the application actually requires.
Report correctness and performance as separate results
Record the final count and elapsed seconds for each order together with the compiler, optimization settings, worker count and iterations. If repeating runs, vary order and retain the observations rather than selecting only the fastest value. This program does not assert that atomic operations on its chosen integer type are always lock-free on every target; an implementation may use auxiliary mechanisms. Investigate that property through a suitable query or generated-code inspection when it matters. Keep three conclusions separate: the count assertion passed, a particular runtime was observed here, and another publication protocol needs its own ordering argument. No universal throughput or latency guarantee follows from this small experiment.