std::atomic_flag
STD::原子[医]旗子
Defined in header | | |
---|---|---|
class atomic_flag; | | (since C++11) |
std::atomic_flag是原子布尔类型。不像所有的专门性std::atomic,保证没有锁。不像std::atomic<bool>,,,std::atomic_flag不提供加载或存储操作。
成员函数
(constructor) | constructs an atomic_flag (public member function) |
---|---|
operator= | the assignment operator (public member function) |
clear | atomically sets flag to false (public member function) |
test_and_set | atomically sets the flag to true and obtains its previous value (public member function) |
例
自旋锁互斥体可以在用户空间中使用原子实现。[医]旗子。
二次
#include <thread>
#include <vector>
#include <iostream>
#include <atomic>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n)
{
for (int cnt = 0; cnt < 100; ++cnt) {
while (lock.test_and_set(std::memory_order_acquire)) // acquire lock
; // spin
std::cout << "Output from thread " << n << '\n';
lock.clear(std::memory_order_release // release lock
}
}
int main()
{
std::vector<std::thread> v;
for (int n = 0; n < 10; ++n) {
v.emplace_back(f, n
}
for (auto& t : v) {
t.join(
}
}
二次
产出:
二次
Output from thread 2
Output from thread 6
Output from thread 7
...<exactly 1000 lines>...
二次
另见
atomic_flag_test_and_setatomic_flag_test_and_set_explicit (C++11)(C++11) | atomically sets the flag to true and returns its previous value (function) |
---|---|
atomic_flag_clearatomic_flag_clear_explicit (C++11)(C++11) | atomically sets the value of the flag to false (function) |
ATOMIC_FLAG_INIT (C++11) | initializes an std::atomic_flag to false (macro constant) |
C原子文档[医]旗子
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。