Hard
Two threads, one relaxed counter
Two threads each run this worker function 100,000 iterations, incrementing a shared std::atomic<int> with memory_order_relaxed. What does main print after both threads join?
main.cpp
#include <atomic>
#include <thread>
#include <iostream>
std::atomic<int> counter{0};
void worker() {
for (int i = 0; i < 100000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
t1.join();
t2.join();
std::cout << counter.load(std::memory_order_relaxed) << std::endl;
}68 of 117 in C++