yor*_*eta 3 c++ concurrency atomic c++11
std::memory_order_relaxed在以下代码中使用是否正确?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我有一个方法调用计数器.计数器何时实际递增(/*1*/)无关紧要,如果它会增加一段时间就足够了.但是当我调用atomic::load(/*2*/)时,所有已经进行的计数器更改都应该是可见的.
它是正确使用std::memory_order_relaxed的线路/*1*/和/*2*/?