簡體   English   中英

帶有 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();
    }
}

在循環std::this_thread::sleep_for中不寫自旋鎖是否有原因? 通常,當我編寫自旋鎖時,我總是讓線程進入睡眠狀態,而不是讓處理器在循環中一直運行線程。 我做錯了嗎?

自旋鎖是指線程進入睡眠狀態,而是運行(循環)直到滿足特定條件。 它不涉及到 kernel 的旅行(除非您已經在內核中)。

使用this_thread::sleep_for會破壞目的,即線程將被 kernel 置於睡眠狀態,並在稍后kernel重新安排執行。 這樣的解決方案不再是自旋鎖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM