2

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.

a3f
  • 8,517
  • 1
  • 41
  • 46
user6672353
  • 21
  • 1
  • 2

1 Answers1

3

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.

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.

Community
  • 1
  • 1
a3f
  • 8,517
  • 1
  • 41
  • 46