hn.today

A quick overview of atomics in C

lemire.me4 points0 comments
Screenshot of A quick overview of atomics in C

This is a concise technical overview of concurrency primitives in C, focusing on threads and atomic variables. It explains that C11 introduced a threads API (threads.h) and stdatomic.h, but threads.h is optional (guarded by STDC_NO_THREADS), is absent on macOS, and only appeared in glibc 2.28, so many projects use pthreads instead. It defines a data race as two threads accessing the same non-atomic variable with no ordering when at least one writes, which makes behavior undefined. Atomic types guarantee that reads return values that were actually written; hardware often provides aligned atomic loads/stores for common sizes, but the C language requires explicit atomic types to get defined behavior across compilers.

The write explains memory-ordering models: sequentially consistent atomics are ordered but expensive; relaxed atomics preserve a single modification order for an object without cross-variable ordering; release and acquire semantics provide a practical middle ground. Release means “if you observe this write, you observe prior operations,” and acquire means “after this read, subsequent operations happen after it.” The post illustrates why that matters with a resource-plus-reference-count example where decrements and accesses can be reordered unless paired with appropriate release/acquire operations.

Read on lemire.me0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.