当前位置:网站首页>std::atomic_flag的test_and_set函数理解

std::atomic_flag的test_and_set函数理解

2022-08-09 17:24:00 hellozhengyuan

std::atomic_flag test_and_set函数理解

 

std::atomic_flag的test_and_set函数原型如下:

bool test_and_set(std::memory_order order = std::memory_order_seq_cst) volatile noexcept;	(1)	(since C++11)
bool test_and_set(std::memory_order order = std::memory_order_seq_cst) noexcept;	(2)	(since C++11)

Atomically changes the state of a std::atomic_flag to set (true) and returns the value it held before.

 

atomic_flag只能有3个状态:

  • 未设置(定义时未初始化,在c++20以后在定义时自动初始化为false,即在c++20以后此状态不再存在)
  • 清除(false)
  • 设置(true)

 

test_and_set函数的理解

此函数有两种语义:

  •     1. test表示先测试(读取当前atomic_flag的值)并返回个这结果值;
  •     2. set表示将atomic_flag状态设置为ture。

可以看出,test_and_set函数的返回值与set的结果没有关系,返回值只表示调用test_and_set函数前的atomic_flag当前的状态。调用此函数后atomic_flag状态一定为true。

可以看出atomic_flag原子变量的操作十分的有限。直到c++20以后才新增test()函数,对atomic_flag状态无修改的只读访问函数

 

原网站

版权声明
本文为[hellozhengyuan]所创,转载请带上原文链接,感谢
https://blog.csdn.net/baidu_20351223/article/details/115767338