Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is atomic<T*> always lock free?

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?

like image 546
Wonter Avatar asked Aug 13 '18 12:08

Wonter


People also ask

Are Atomic locks free?

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.

Is STD atomic bool lock-free?

atomic<bool>. std::atomic_flag i s the only atomic data type that is lock-free.


2 Answers

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.

like image 162
VLL Avatar answered Oct 05 '22 09:10

VLL


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.

like image 28
Caleth Avatar answered Oct 05 '22 08:10

Caleth