并发支持库(2)-原子操作

本文详细介绍了C++中的原子(atomic)类及其使用,包括原子类型、构造函数、成员函数如存储、加载、交换、比较交换等,以及atomic_flag的独特性质,展示了如何利用原子操作实现线程间的同步和数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++中的原子用于实现对象的线程安全的操作,避免数据竞争,每一个原子操作可以看作一个不可分割地整体。

本文章的代码库:https://gitee.com/gamestorm577/CppStd

atomic

atomic是一个类模板,每个atomic模板的实例化都定义了一个原子类型。对于一个原子对象,不同的线程对对象的写入和读取是安全的。atomic不能复制,也不能移动。

c++中为一些基本类型定义了atomic的别名,例如:

using atomic_bool   = atomic<bool>;
using atomic_char   = atomic<char>;
using atomic_schar  = atomic<signed char>;
using atomic_uchar  = atomic<unsigned char>;
using atomic_short  = atomic<short>;
using atomic_ushort = atomic<unsigned short>;
using atomic_int    = atomic<int>;
using atomic_uint   = atomic<unsigned int>;
using atomic_long   = atomic<long>;
using atomic_ulong  = atomic<unsigned long>;
using atomic_llong  = atomic<long long>;
using atomic_ullong = atomic<unsigned long long>;

成员函数

构造函数

默认构造,或者用一个值构造一个atomic对象。代码示例:

std::atomic<int> a_i(20);
std::cout << "a_i = " << a_i << std::endl;

输出结果:

a_i = 20

赋值函数

将值原子地赋值给对象。代码示例:

std::atomic<int> a_i(20);
std::cout << "a_i = " << a_i << std::endl;
a_i = 25;
std::cout << "a_i = " << a_i << std::endl;

输出结果:

a_i = 20
a_i = 25

is_lock_free

检查原子类型的原子操作是否是无锁的。代码示例:

struct A
{
    int a[100];
};

struct B
{
    int x;
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lucy_stone

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值