Is it correct to use memory_order_relaxed at this code?

atomic, c++, c++11, concurrency

Solution

Yes, that's fine. The thread joining provides the necessary synchronization point that ensures that the final `load()` sees the correct value.

Problem

Is it correct to use `std::memory_order_relaxed` at the following code? ``` #include <atomic> #include <array> #include <iostream> #include <thread> using namespace std; int main() { std::atomic<int> counter(0); constexpr size_t thread_count = 10; std::array<std::thread, thread_count> threads; for (auto& th : threads) { th = std::thread([&counter]() { for (int j = 0; j < 100; ++j) { /*1*/ counter.fetch_add(1, std::memory_order_relaxed); } }); } for (auto& th : threads) th.join(); /*2*/ std::cout << counter.load(std::memory_order_relaxed) << std::endl; return 0; } ``` I have a method call counter. It doesn't matter when the counter will be actually incremented (`/*1*/`), it's enough if it will be incremented some time. But when I call `atomic::load` (`/*2*/`), all counter changes that have been made should be visible. Is it correct to use `std::memory_order_relaxed` in lines `/*1*/` and `/*2*/`?

Original source