使用 std::atomic_flag 自旋锁 - 是否让线程休眠?

Spin lock with std::atomic_flag - put the thread to sleep or not?

来自cppreference

#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))  // acquire lock
             ; // spin  <===================== no sleep
        std::cout << "Output from thread " << n << '\n';
        lock.clear(std::memory_order_release);               // release lock
    }
}
 
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();
    }
}

不在自旋锁 while 循环 std::this_thread::sleep_for 中写入是否有原因?通常,当我编写自旋锁时,我总是让线程休眠,而不是让处理器 运行 线程一直处于循环中。我做错了吗?

A spinlock 是指线程 不是 进入睡眠状态,而是 运行 (循环)直到满足特定条件。它不涉及内核之旅(除非您已经在内核中)。

使用 this_thread::sleep_for 会破坏目的,即线程将被 内核 置于休眠状态,并由 [=17= 重新安排执行]kernel 稍后。这样的解决方案不再是自旋锁。