On my MAC OS, atomic<T*>
is lock free.
#include <iostream>
#include <atomic>
int main() {
std::cout << std::atomic<void*>().is_lock_free() << std::endl;
return 0;
}
output: 1
I want to know if atomic<T*>
is always lock free?
Is there a reference to introduce it?
atomic<T> variables don't use locks (at least where T is natively atomic on your platform), but they're not lock-free in the sense above. You might use them in the implementation of a lock-free container, but they're not sufficient on their own.
atomic<bool>. std::atomic_flag i s the only atomic data type that is lock-free.
The standard allows implementing any atomic type (with exception of std::atomic_flag) to be implemented with locks. Even if the platform would allow lock-free atomics for some type, the standard library developers might not have implemented that.
If you need to implement something differently when locks are used, this can be checked at compile time using ATOMIC_POINTER_LOCK_FREE
macro.
No, it is not safe to assume that any particular platform's implementation of std::atomic
is always lock free.
The standard specifies some marker macros, including ATOMIC_POINTER_LOCK_FREE
, which indicates either pointers are never, sometimes or always lock free, for the platform in question.
You can also get an answer from std::atomic<T *>::is_always_lock_free
, for your particular T
.1
Note 1: A given pointer type must be consistent, so the instance method std::atomic<T *>::is_lock_free()
is redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With