原型: struct atomic_flag;
Atomic flags是boolean atomic 对象, 支持两种操作, test-and-set 和 clear.
Atomic flags是 lock-free(原子操作), 是唯一被保证的lock-free 原子操作的.
atomic_flag() noexcept = default;
atomic_flag (const atomic_flag& T) = delete; // atomic_flag不能被 copied/moved
atomic_flag的状态 没有在 构造函数中指定, 除非 显示地被 初始化为 ATOMIC_FLAG_INIT.
函数原型为:
bool test_and_set (memory_order sync = memory_order_seq_cst) volatile noexcept;
bool test_and_set (memory_order sync = memory_order_seq_cst) noexcept;
1. 如果atomic flags设置过, 则 test_and_set()返回true
2. 否则, 返回false
test_and_set() 函数是 atomic原子操作, read-modify-write原子操作.
memory order是对atomic操作的一直约束.
#include
#include
#include // std::mutex
#include // std::atomic, std::atomic_flag, ATOMIC_FLAG_INIT
#include // std::vector
#include // std::thread, std::thread::id
#include // std::chrono::seconds
#include // std::put_time
#include // std::time_t, std::tm, std::localtime, std::mktime
#include // std::stringstream
std::atomic_flag lock_stream ;
std::stringstream stream;
std::mutex mu;
void append_number(int x) {
mu.lock();
if (lock_stream.test_and_set()) { std::cout << "true" << std::endl;}
else {std::cout << "false" << std::endl;}
if (lock_stream.test_and_set()) { std::cout << "true" << std::endl; }
else { std::cout << "false" << std::endl; }
lock_stream.clear();
mu.unlock();
}
int main()
{
std::vector threads;
for (int i = 1; i <= 5; ++i) threads.push_back(std::thread(append_number, i));
for (auto& th : threads) th.join();
std::cout << stream.str();
return 0;
}
第一次调用 test_and_set() 返回 false, 此时并设置 atomic_flag; 第二次调用 test_and_set() 返回true.
clear() 回清除 atomic_flag的设置, 此后第一次调用 test_and_set() 返回false.
函数原型为:
void clear (memory_order sync = memory_order_seq_cst) volatile noexcept;
void clear (memory_order sync = memory_order_seq_cst) noexcept;
函数 clear() 会clear atomic_flag, 并使得 atomic_flag::test_and_set()函数 返回false.
clear()函数是 atomic原子操作, 并且 follow 指定的 memory ordering.