谁能告诉我std::atomic::is_lock_free()是否像constexpr一样不是静态的?使它为非静态和/或为非constexpr对我来说没有任何意义。
最佳答案
如cppreference所述:
All atomic types except for std::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 be sometimes lock-free, e.g. if only aligned memory accesses are naturally atomic on a given architecture, misaligned objects of the same type have to use locks.
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.
正如其他许多人提到的那样,
std::is_always_lock_free
可能正是您真正想要的。编辑:明确起见,C++对象类型具有一个对齐值,该对齐值将其实例的地址限制为仅乘以2的某些倍数(
[basic.align]
)。这些对齐值是针对基本类型的实现定义的,不需要等于类型的大小。它们也可能比硬件实际支持的条件更严格。例如,x86(大多数情况下)支持不对齐的访问。但是,您会发现大多数具有x86的
alignof(double) == sizeof(double) == 8
的编译器,因为未对齐的访问存在许多缺点(速度,缓存,原子性...)。但是例如#pragma pack(1) struct X { char a; double b; };
或alignas(1) double x;
允许您使用“未对齐”的double
。因此,当cppreference谈论“对齐的内存访问”时,大概是按照硬件类型的自然对齐方式进行的,而不是以与其对齐要求(即UB)相抵触的方式使用C++类型。这是更多信息:What's the actual effect of successful unaligned accesses on x86?
另请在下面查看 @Peter Cordes 的有见地的评论!
关于c++ - 为什么std::atomic <T>::is_lock_free()和constexpr一样不是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58816223/