#1772mediumC++ & Systems
False Sharing in a Parallel Counter
Two threads each increment their own counter one hundred million times:
#include <thread>
long counts[2] = {0, 0};
void work(int i) {
for (int k = 0; k < 100'000'000; ++k) {
++counts[i];
}
}
int main() {
std::thread t0(work, 0);
std::thread t1(work, 1);
t0.join();
t1.join();
}
On a multicore machine this runs slower than running the two loops sequentially on one thread. What is the most likely cause?
Loading interactive editor…