clinuxatomic

How to use atomic variables in C?


I need to use an atomic variable in C as this variable is accessed across different threads. Don't want a race condition.

My code is running on CentOS. What are my options?


Solution

  • If you are using GCC on your CentOS platform, then you can use the __atomic built-in functions.

    Of particular interest might be this function:

    ā€” Built-in Function: bool __atomic_always_lock_free (size_t size, void *ptr)
    This built-in function returns true if objects of size bytes always generate lock free atomic instructions for the target architecture. size must resolve to a compile-time constant and the result also resolves to a compile-time constant.

    ptr is an optional pointer to the object that may be used to determine alignment. A value of 0 indicates typical alignment should be used. The compiler may also ignore this parameter.

          if (_atomic_always_lock_free (sizeof (long long), 0))