Can I perform arithmetic operations on an atomic variable directly?
Since I find the C standard library provides a lot of utility functions like atomic_fetch_add
to perform the addition between an atomic variable and a non-atomic variable. But, I am curious since the variable is atomic, can I have arithmetic operations directly on it? Like in the code shown below:
#include <threads.h>#include <stdio.h>#include <stdatomic.h>atomic_int i = 0;int run(void* v) { i += 100; // <- is this operaiton thread-safe? // atomic_fetch_add(&i, 100); printf("%d\n", i); return thrd_success;}int main(void) { thrd_t thread; thrd_create(&thread, run, NULL); thrd_join(thread, NULL); return 0; }