Simple C11 atomics: atomic_flag

C11 (and similar C++11) has a new primitive type in its new toolbox for atomics: atomic_flag. As you’d perhaps imagine from the name, a variable of that type has two different states, called “cleared” and “set”, and access to it is atomic. It is even guaranteed to be “lock-free”, see below.

Sounds like atomic_flag is the same as _Atomic(_Bool), doesn’t it? Not quite. Access to it is even more restricted than for a _Bool, however it might be more efficient.

Continue reading “Simple C11 atomics: atomic_flag”


Emulating C11 compiler features with gcc: _Atomic

The new support for atomic operations in C11 is probably the most useful one. Support for atomic instructions is present in all commodity processors since at least 20 years, but a standardized interface in one of the main programming languages was really missing. Up to now you always had to implement stubs for these operations in assembler. This by itself was not as difficult for a given platform, but writing platform independent code quickly became tedious.

P99 now has an emulation of parts of these features that allow you to use them in a preview for C11. This implementation mainly uses (again) extensions of the gcc family. It should even work for older versions of gcc that don’t implement their __sync_.. built-in.

Continue reading “Emulating C11 compiler features with gcc: _Atomic”

Emulating C11 compiler features with gcc: _Generic

Besides the new interfaces for threads and atomic operations that I already mentioned earlier, others of the new features that come with C11 are in reality already present in many compilers. Only that not all of them might agree upon the syntax, and especially not with the new syntax of C11. So actually emulating some these features is already possible and I implemented some of them in P99 on the base of what gcc provides: these are

  • static_assert (or _Static_assert) to make compile time assertions (a misnomer, again!)
  • alignof (or _Alignof) to get the alignment constraint for a type
  • alignas (of _Alignas) to constraint the alignment of objects or struct members. Only the variant that receives a constant expression is directly supported. The variant with a type argument can be obtained simply by alignas(alignof(T)).
  • noreturn (or _Noreturn) to specify that a function is not expected to return to the caller
  • thread_local (or _Thread_local) for thread local storage
  • _Generic for type generic expression.

The most interesting among them is probably the latter feature, type generic expressions.
Continue reading “Emulating C11 compiler features with gcc: _Generic”