Namespaces
Variants

std:: atomic_flag_test_and_set, std:: atomic_flag_test_and_set_explicit

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
atomic_flag_test_and_set atomic_flag_test_and_set_explicit
(C++11) (C++11)
定义于头文件 <atomic>
bool atomic_flag_test_and_set ( volatile std:: atomic_flag * obj ) noexcept ;
(1) (C++11 起)
bool atomic_flag_test_and_set ( std:: atomic_flag * obj ) noexcept ;
(2) (C++11 起)
bool atomic_flag_test_and_set_explicit ( volatile std:: atomic_flag * obj,
std:: memory_order order ) noexcept ;
(3) (C++11 起)
bool atomic_flag_test_and_set_explicit ( std:: atomic_flag * obj,
std:: memory_order order ) noexcept ;
(4) (C++11 起)

原子地修改由 obj 指向的 std::atomic_flag 状态为置位状态( true ),并返回其先前持有的值。

1,2) 内存同步顺序为 std:: memory_order_seq_cst
3,4) 内存同步顺序为 order

目录

参数

obj - 指向要访问的 std::atomic_flag 的指针
order - 内存同步顺序

返回值

先前由 obj 所指向标志持有的值。

注释

std::atomic_flag_test_and_set std::atomic_flag_test_and_set_explicit 可分别实现为 obj - > test_and_set ( ) obj - > test_and_set ( order )

示例

自旋锁互斥量可以在用户空间使用 std::atomic_flag 实现。

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
std::atomic_flag lock = ATOMIC_FLAG_INIT;
void f(int n)
{
    for (int cnt = 0; cnt < 100; ++cnt)
    {
        while (std::atomic_flag_test_and_set_explicit(&lock, std::memory_order_acquire))
            ; // 自旋直到获取锁
        std::cout << "Output from thread " << n << '\n';
        std::atomic_flag_clear_explicit(&lock, 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>...

参见

无锁布尔原子类型
(类)
原子地将标志值设置为 false
(函数)
为给定原子操作定义内存顺序约束
(枚举)
C 文档 用于 atomic_flag_test_and_set , atomic_flag_test_and_set_explicit