原子变量是无锁的吗? [英] Are atomic variables lock-free?

查看:57
本文介绍了原子变量是无锁的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们谈论原子变量,例如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.

这篇关于原子变量是无锁的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆