【问题标题】:Spin lock with std::atomic_flag - put the thread to sleep or not?带有 std::atomic_flag 的自旋锁 - 是否让线程进入睡眠状态?
【发布时间】:2021-06-05 12:12:16
【问题描述】:

来自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背后有什么原因吗?通常,当我编写自旋锁时,我总是让线程进入睡眠状态,而不是让处理器在循环中一直运行线程。我做错了吗?

【问题讨论】:

  • 这是一个判断电话。旋转通常是因为您不想要互斥锁(内核调用、调度程序)之类的开销。旋转和屈服介于两者之间。
  • @RichardCritten 和 std::this_thread::sleep_for 会跳转到内核调用吗?
  • 它必须。 Yielding 是一个操作系统调度程序函数 - 使线程进入睡眠状态,保留其状态并将线程添加到将来要调度的线程列表中。

标签: c++ multithreading c++11 thread-safety std


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 1970-01-01
    • 2012-08-08
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多