std::atomic_flag
來自 cppreference.com
定義於標頭檔案 <atomic> |
||
class atomic_flag; |
(C++11 起) | |
std::atomic_flag
是一種原子布林型別。與 std::atomic 的所有特化不同,它保證是無鎖的。與 std::atomic<bool> 不同,std::atomic_flag
不提供載入或儲存操作。
[編輯] 成員函式
構造一個 atomic_flag (公開成員函式) | |
[已刪除] |
賦值運算子(已刪除) (公開成員函式) |
原子地將標誌設定為 false (public member function) | |
原子地將標誌設定為 true 並獲取其先前值 (public member function) | |
(C++20) |
原子地返回標誌的值 (public member function) |
(C++20) |
阻塞執行緒直到被通知且原子值改變 (public member function) |
(C++20) |
通知至少一個等待原子物件的執行緒 (public member function) |
(C++20) |
通知所有被原子物件阻塞的執行緒 (public member function) |
[編輯] 示例
可以使用 atomic_flag 在使用者空間中實現一個 自旋鎖 互斥量演示。請注意,自旋鎖互斥量在實踐中是極其可疑的。
執行此程式碼
#include <atomic> #include <iostream> #include <mutex> #include <thread> #include <vector> class mutex { std::atomic_flag m_{}; public: void lock() noexcept { while (m_.test_and_set(std::memory_order_acquire)) #if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L // Since C++20, locks can be acquired only after notification in the unlock, // avoiding any unnecessary spinning. // Note that even though wait guarantees it returns only after the value has // changed, the lock is acquired after the next condition check. m_.wait(true, std::memory_order_relaxed) #endif ; } bool try_lock() noexcept { return !m_.test_and_set(std::memory_order_acquire); } void unlock() noexcept { m_.clear(std::memory_order_release); #if defined(__cpp_lib_atomic_wait) && __cpp_lib_atomic_wait >= 201907L m_.notify_one(); #endif } }; static mutex m; static int out{}; void f(std::size_t n) { for (std::size_t cnt{}; cnt < 40; ++cnt) { std::lock_guard lock{m}; std::cout << n << ((++out % 40) == 0 ? '\n' : ' '); } } int main() { std::vector<std::thread> v; for (std::size_t n{}; n < 10; ++n) v.emplace_back(f, n); for (auto &t : v) t.join(); }
可能的輸出
0 1 1 2 0 1 3 2 3 2 0 1 2 3 2 3 0 1 3 2 0 1 2 3 2 3 0 3 2 3 2 3 2 3 1 2 3 0 1 3 2 3 2 0 1 2 3 0 1 2 3 2 0 1 2 3 0 1 2 3 2 3 2 3 2 0 1 2 3 2 3 0 1 3 2 3 0 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 3 2 0 2 3 2 3 2 3 2 3 2 3 0 3 2 3 0 3 0 3 2 3 0 3 2 3 2 3 0 2 3 0 3 2 0 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9
[編輯] 另請參閱
原子地將標誌設定為 true 並返回其先前的值 (function) | |
(C++11)(C++11) |
原子地將標誌的值設定為 false (function) |
(C++20)(C++20) |
阻塞執行緒直到被通知且標誌改變 (function) |
(C++20) |
通知一個在 atomic_flag_wait 中阻塞的執行緒 (function) |
(C++20) |
通知所有在 atomic_flag_wait 中阻塞的執行緒 (function) |
(C++11) |
將 std::atomic_flag 初始化為 false (macro constant) |
C 文件 關於 atomic_flag
|