|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <atomic> | ||
template<class T> bool atomic_is_lock_free(constvolatilestd::atomic<T>* obj)noexcept; | (1) | (since C++11) |
template<class T> bool atomic_is_lock_free(conststd::atomic<T>* obj)noexcept; | (2) | (since C++11) |
#define ATOMIC_BOOL_LOCK_FREE /* unspecified */ #define ATOMIC_CHAR_LOCK_FREE /* unspecified */ | (3) | (since C++11) |
#define ATOMIC_CHAR8_T_LOCK_FREE /* unspecified */ | (4) | (since C++20) |
Contents |
| obj | - | pointer to the atomic object to examine |
true if*obj is a lock-free atomic,false otherwise.
All atomic types except forstd::atomic_flag may be implemented using mutexes or other locking operations, rather than using the lock-free atomic CPU instructions. Atomic types are also allowed to besometimes lock-free: for example, if only some sub-architectures support lock-free atomic access for a given type (such as theCMPXCHG16B instruction on x86-64), whether atomics are lock-free may not be known until runtime.
The C++ standard recommends (but does not require) that lock-free atomic operations are also address-free, that is, suitable for communication between processes using shared memory.
#include <atomic>#include <iostream>#include <utility> struct A{int a[4];};struct B{int x, y;}; int main(){std::atomic<A> a;std::atomic<B> b;std::cout<<std::boolalpha<<"std::atomic<A> is lock free? "<< std::atomic_is_lock_free(&a)<<'\n'<<"std::atomic<B> is lock free? "<< std::atomic_is_lock_free(&b)<<'\n';}
Possible output:
std::atomic<A> is lock free? falsestd::atomic<B> is lock free? true
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 3249 | C++11 | atomic_is_lock_free was specified via pointers, whichwas ambiguous and might accept invalid pointer values | specified via atomic objects |
| checks if the atomic object is lock-free (public member function of std::atomic<T>)[edit] | |
(C++11) | the lock-free boolean atomic type (class)[edit] |
[static](C++17) | indicates that the type is always lock-free (public static member constant of std::atomic<T>)[edit] |
(deprecated in C++20)(removed in C++26) | specializes atomic operations forstd::shared_ptr (function template) |
C documentation foratomic_is_lock_free | |
C documentation forATOMIC_*_LOCK_FREE | |