dimanche 24 avril 2022

polling C++ atomics for thread synchronization

I would like to understand if the following way of thread sync using atomics is defined behavior, i.e. does the usage of atomic guarantee that a cached version of the atomic variable will not be used instead ? If it is defined behavior is the usage of std::memory_order::relaxed okay or does one need to use acquire/release barriers instead?

#include <thread>
#include <atomic>
#include <iostream>

std::atomic<bool> flag {false};

int main()  
{    
    std::thread t1([]() {
        while (!flag.load()) {            
        }
    }); 
    flag.store(true, std::memory_order_relaxed);
    t1.join();
    std::cout << "Done\n";
}

Aucun commentaire:

Enregistrer un commentaire