mercredi 24 juin 2020

std::memory_order_relaxed example in cppreference.com

The cppreference.com gives the following example for use of std::memory_order_relaxed. (https://en.cppreference.com/w/cpp/atomic/memory_order)

#include <vector>
#include <iostream>
#include <thread>
#include <atomic>
 
std::atomic<int> cnt = {0};
 
void f()
{
    for (int n = 0; n < 1000; ++n) {
        cnt.fetch_add(1, std::memory_order_relaxed);
    }
}
 
int main()
{
    std::vector<std::thread> v;
    for (int n = 0; n < 10; ++n) {
        v.emplace_back(f);
    }
    for (auto& t : v) {
        t.join();
    }
    std::cout << "Final counter value is " << cnt << '\n';
}

Output: Final counter value is 10000

Is this a correct/sound example (Can a standard complaint compiler introduce optimizations that will yield different answers?). Since std::memory_order_relaxed only guarantee the operation be atomic, one thread may not see an update from another thread. Am I missing something?

Aucun commentaire:

Enregistrer un commentaire