名稱空間
變體
操作

std::atomic_flag_test_and_set, std::atomic_flag_test_and_set_explicit

來自 cppreference.com
< cpp‎ | atomic
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
atomic_flag_test_and_setatomic_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 起)

原子地將指向 std::atomic_flagobj 的狀態更改為 set(true),並返回它之前持有的值。

1,2) 記憶體同步順序為 std::memory_order_seq_cst
3,4) 記憶體同步順序為 order

目錄

[編輯] 引數

obj - 指向 std::atomic_flag 的指標,用於訪問
順序 - 記憶體同步順序

[編輯] 返回值

之前由 obj 所指向的標誌持有的值。

[編輯] 注意

std::atomic_flag_test_and_setstd::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))
            ; // spin until the lock is acquired
        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