dimanche 7 mars 2021

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

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

Is there a reasoning behind not writing in the spin-lock while loop std::this_thread::sleep_for? Normally when I write spin locks I always send the thread to sleep not to make processor run the thread all the time in the loop for nothing. Am I doing it wrong?

Aucun commentaire:

Enregistrer un commentaire