Hard
Two counters in one struct
Two threads run concurrently, each hammering a different atomic counter in the same struct on separate CPU cores. What is true about this program?
main.cpp
#include <atomic>
#include <thread>
struct Counters {
std::atomic<long> a{0};
std::atomic<long> b{0}; // (1) adjacent to 'a', no padding between them
};
Counters counters;
void bumpA() {
for (long i = 0; i < 100'000'000; ++i)
counters.a.fetch_add(1, std::memory_order_relaxed);
}
void bumpB() {
for (long i = 0; i < 100'000'000; ++i)
counters.b.fetch_add(1, std::memory_order_relaxed);
}
int main() {
std::thread t1(bumpA);
std::thread t2(bumpB);
t1.join();
t2.join();
// counters.a == counters.b == 100'000'000, always
}60 of 117 in C++