问题描述
当我们谈论原子变量,例如C ++ 11的atomic<>
时,它是无锁的吗?还是无锁性有所不同?如果我使用原子变量管理队列,它会比无锁队列慢吗?
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?
推荐答案
该标准未指定原子对象是否为无锁对象.在不为类型T提供无锁原子操作的平台上,atomic<T>
对象可以使用互斥锁实现,而该互斥锁不是无锁的.在这种情况下,任何在实现中使用这些对象的容器也不是无锁的.
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.
该标准确实提供了一种检查atomic<T>
变量是否无锁的方法:您可以使用var.is_lock_free()
或atomic_is_lock_free(&var)
.确保这些函数在给定程序执行时始终为相同类型T
返回相同的值.对于int
之类的基本类型,还提供了宏(例如ATOMIC_INT_LOCK_FREE
),这些宏指定是否可以使用对该类型的无锁原子访问.
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.
这篇关于原子变量是无锁的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!