is_lock_free() 恆為 true)test_and_set() (原子讀取並置真)、clear() (原子置假)ATOMIC_FLAG_INIT 或 {} (C++20 起可直接預設構造)#include#include #include #include #include using namespace std; atomic_flag lock_stream = ATOMIC_FLAG_INIT; stringstream stream; void append_number(int x) { // 自旋等待鎖釋放 while (lock_stream.test_and_set()) { // busy-wait,可加 this_thread::yield() 降低 CPU 佔用 } // 臨界區 stream << "thread #" << x << '\n'; // 釋放鎖 lock_stream.clear(); } int main() { vector threads; for (int i = 1; i <= 10; ++i) { threads.emplace_back(append_number, i); } for (auto& t : threads) t.join(); cout << stream.str(); return 0; }
thread #1 thread #2 thread #3 thread #4 thread #5 thread #6 thread #7 thread #8 thread #9 thread #10
thread #3 thread #1 thread #5 thread #2 ... (輸出順序不可預測,甚至單行字符可能交錯)
bool old = flag; flag = true; return old;while (flag.test_and_set()) { /* wait */ }class SpinLock {
atomic_flag flag = ATOMIC_FLAG_INIT;
public:
void lock() { while (flag.test_and_set(memory_order_acquire)) {} }
void unlock() { flag.clear(memory_order_release); }
};
// RAII 包裝
class SpinLockGuard {
SpinLock& mtx;
public:
explicit SpinLockGuard(SpinLock& m) : mtx(m) { mtx.lock(); }
~SpinLockGuard() { mtx.unlock(); }
};
// 使用
SpinLock mtx;
void safeFunc() {
SpinLockGuard g(mtx);
// 臨界區...
}
atomic_flag 是 C++ 原子操作的基石,以最小原語實現互斥。理解其 test_and_set/clear 語義、記憶體序配合、自旋特性,能在高效能、低延遲場景下構建高效同步機制。但切記:自旋鎖僅適合極短臨界區,濫用會嚴重浪費 CPU 週期。