I suppose I can use __atomic_compare_exchange_n
in place of __atomic_test_and_set
.
Is there any performance benefit of one over other for using these builtins for boolean values?
Any input other than number of arguments is appreciated.
You are better off using the API provided by C11's <stdatomic.h>
. The __atomic
builtins are just how GCC implements them under the hood, using standard API makes your code more portable.
__atomic_test_and_set
is what GCC translates atomic_flag_test_and_set
to.
__atomic_compare_exchange_n
is atomic_compare_exchange
.
gcc6 on AMD64 with -O2
compiles
if (atomic_flag_test_and_set(&atomic_flag_var) == 0) {
printf("Hello World\n");
}
if (atomic_compare_exchange_strong(&atomic_var, &clear, 1)) {
printf("Hello World\n");
}
to a xchg
followed by a test
in the first case. The other one expectedly to a cmpxchg
. It's unlikely, that you'll experience any noticeable difference between the two. See this answer: Relative performance of swap vs compare-and-swap locks on x86.
So, which one to use? If you need an atomic flag, use atomic_flag
. The standard guarantees that this will be lock-free. No such guarantee exists for any of the other _Atomic
types.