C _Atomic Keyword
Example
Create an atomic variable and add 1 to it two times:
_Atomic int counter = 0;
counter++;
counter++;
printf("%d", counter);
Definition and Usage
The _Atomic keyword makes a variable atomic. This means that every read or change of the variable happens in one complete step, which cannot be interrupted.
This is important in programs that use threads. A thread is a part of a program that runs at the same time as other parts. If two threads change a normal variable at the same time, one of the changes can get lost. With _Atomic, a change like counter++ is safe.
If you include <stdatomic.h>, you can write atomic_int instead of _Atomic int. The header also has functions for atomic variables.
Related Pages
The _Thread_local keyword gives each thread its own copy of a variable.
Read more about variables in our C Variables Tutorial.