C++ 11原子类型 -- atomic_flag
程序员文章站
2024-03-14 11:14:28
...
std::对象可以是两种状态之一:设置或清除,且须用ATOMIC_FLAG_INIT初始化,这会将该标志初始化为清除状态(此标志总是以清除状态初始化的),如下:
std::atomic_flag flag=ATOMIC_FLAG_INIT;
只支持两种原子操作:
test_and_set函数:如果atomic_flag对象已经被设置,则返回true; 如果atomic_flag对象未被设置,则设置之,返回false。
std::atomic_flag可用于多线程之间的同步操作,使用atomic_flag可实现mutex
example1:用atomic_flag可实现自旋锁:
example2:
https://en.cppreference.com/w/cpp/atomic/atomic_flag
A spinlock mutex can be implemented in userspace using an atomic_flag
#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();
}
}