Consider the following code that writes the same value to the same memory location from multiple threads:
void f(int* buf, int n, int* p) {
for(int i = 0; i < n; i++)
buf[i] = i;
*p = buf[n/2];
}
void g(int* buf, int n) {
int x1, x2;
thread t1(f, buf, n, &x1);
thread t2(f, buf, n, &x2);
t1.join();
t2.join();
assert(x1 == x2);
}
Although it’s interesting, I’m of less concern of what guarantees the standard gives, since I guess it gives none. What I do care is what will be the behavior of the above code on real-world multiprocessor hardware. Will the assert always pass or there’s any chance of a race-condition, cache synchronization problems, etc..?
Memory models with regards to multi-treading concern when the effects of writes made by one thread are observable by another thread. In the code you posted both threads write the same values into the same memory location, so it doesn’t matter which thread’s write
buf[n/2]reads, either will do.Modern processors employ cache coherency protocols, such as MESI, so when the threads write to the buffer concurrently there is going to be a lot of messages sent between the CPUs to synchronize the cache lines holding the buffer making it run much slower than in non-concurrent scenario (false sharing effect).
Here it doesn’t matter if the writes are atomic or not, since both threads write the same values to the same memory locations. There is a race, but it doesn’t matter which thread wins because the observed values are going to be the same even with partial writes.