std::atomic_flag

定义于头文件 <atomic>
class atomic_flag;
(C++11 起)

std::atomic_flag 是原子布尔类型。不同于所有 std::atomic 的特化,它保证是免锁的。不同于 std::atomic<bool>std::atomic_flag 不提供加载或存储操作。

成员函数

构造 atomic_flag
(公开成员函数)
赋值运算符
(公开成员函数)
原子地设置标志为 false
(公开成员函数)
原子地设置标志为 true 并获得其先前值
(公开成员函数)

示例

可于用户空间用 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))  // 获得锁
             ; // 自旋
        std::cout << "Output from thread " << n << '\n';
        lock.clear(std::memory_order_release);               // 释放锁
    }
}
 
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>...

参阅

原子地设置标志为 true 并返回其先前值
(函数)
原子地设置标志值为 false
(函数)
std::atomic_flag 初始化为 false
(宏常量)
atomic_flagC 文档

版本历史

  • (当前 | 先前 2017年9月13日 (三) 04:06Fruderica讨论 | 贡献. . (1,709字节) (-318). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 07:18P12bot讨论 | 贡献 . . (2,027字节) (-153). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2013年2月21日 (四) 04:45Steffens讨论 | 贡献 . . (2,180字节) (-12). . (撤销)
  • 当前 | 先前 2013年2月21日 (四) 04:44Steffens讨论 | 贡献 . . (2,192字节) (-298). . (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:26P12bot讨论 | 贡献 . . (2,490字节) (+241). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 09:23P12讨论 | 贡献 . . (2,249字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (2,249字节) (-40). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 13:13P12讨论 | 贡献 . . (2,289字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (2,289字节) (+2,289). . (Translated from the English version using Google Translate)