std::atomic_flag
来自cppreference.com
在标头 <atomic> 定义
|
||
class atomic_flag; |
(C++11 起) | |
std::atomic_flag
是一种原子布尔类型。与所有 std::atomic 的特化不同,它保证是免锁的。与 std::atomic<bool> 不同,std::atomic_flag
不提供加载或存储操作。
[编辑] 成员函数
构造 atomic_flag (公开成员函数) | |
赋值运算符 (公开成员函数) | |
原子地设置标志为 false (公开成员函数) | |
原子地设置标志为 true 并获得其先前值 (公开成员函数) | |
(C++20) |
原子地返回标志的值 (公开成员函数) |
(C++20) |
阻塞线程直到被提醒且原子值更改 (公开成员函数) |
(C++20) |
提醒至少一个在原子对象上的等待中阻塞的线程 (公开成员函数) |
(C++20) |
提醒所有在原子对象上的等待中阻塞的线程 (公开成员函数) |
[编辑] 示例
可于用户空间用 atomic_flag 实现自旋锁互斥体。注意在实践中使用自旋锁通常是错误。
运行此代码
#include <atomic> #include <iostream> #include <mutex> #include <thread> #include <vector> class mutex { std::atomic_flag m_{}; public: void lock() noexcept { while (m_.test_and_set(std::memory_order_acquire)) #if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L // C++ 20 起可以仅在 unlock 中通知后才获得锁,从而避免任何无效自旋 // 注意,即使 wait 保证一定在值被更改后才返回,但锁定是在下一次执行条件时完成的 m_.wait(true, std::memory_order_relaxed) #endif ; } bool try_lock() noexcept { return !m_.test_and_set(std::memory_order_acquire); } void unlock() noexcept { m_.clear(std::memory_order_release); #if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L m_.notify_one(); #endif } }; static mutex m; static int out{}; void f(std::size_t n) { for (std::size_t cnt{}; cnt < 40; ++cnt) { std::lock_guard lock{m}; std::cout << n << ((++out % 40) == 0 ? '\n' : ' '); } } int main() { std::vector<std::thread> v; for (std::size_t n{}; n < 10; ++n) v.emplace_back(f, n); for (auto &t : v) t.join(); }
可能的输出:
0 1 1 2 0 1 3 2 3 2 0 1 2 3 2 3 0 1 3 2 0 1 2 3 2 3 0 3 2 3 2 3 2 3 1 2 3 0 1 3 2 3 2 0 1 2 3 0 1 2 3 2 0 1 2 3 0 1 2 3 2 3 2 3 2 0 1 2 3 2 3 0 1 3 2 3 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 3 2 0 2 3 2 3 2 3 2 3 2 3 0 3 2 3 0 3 0 3 2 3 0 3 2 3 2 3 0 2 3 0 3 2 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
[编辑] 参阅
原子地设置标志为 true 并返回其先前值 (函数) | |
(C++11)(C++11) |
原子地设置标志值为 false (函数) |
(C++20)(C++20) |
阻塞线程,直至被提醒且标志更改 (函数) |
(C++20) |
提醒一个在 atomic_flag_wait 中阻塞的线程 (函数) |
(C++20) |
提醒所有在 atomic_flag_wait 中阻塞的线程 (函数) |
(C++11) |
初始化 std::atomic_flag 为 false (宏常量) |
atomic_flag 的 C 文档
|