When we talk about atomic variables, such as C++11's atomic<>
, is it lock free? Or is lock-freeness something different? If I manage a queue with atomic variables, will it be slower than a lock-free queue?
The standard does not specify if atomic objects are lock-free. On a platform that doesn't provide lock-free atomic operations for a type T, atomic<T>
objects may be implemented using a mutex, which wouldn't be lock-free. In that case, any containers using these objects in their implementation would not be lock-free either.
The standard does provide a way to check if an atomic<T>
variable is lock-free: you can use var.is_lock_free()
or atomic_is_lock_free(&var)
. These functions are guaranteed to always return the same value for the same type T
on a given program execution. For basic types such as int
, There are also macros provided (e.g. ATOMIC_INT_LOCK_FREE
) which specify if lock-free atomic access to that type is available.