Does writing the same value to the same memory location cause a data race?

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);
    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.

There is a race, but in your example both threads will write the same values to the same addresses. Since you are not doing any read-modify-writes, but just writing predetermined numbers, this will be safe in most cases. Writing an int will be an atomic instruction on most systems. The exception would be if you ran this code on a 8-bit microprocessor that uses a sequence of instructions to store an int. In that case it also may still work, but depends on the implementation of the library code that does the multi-byte store.

Need Your Help

Android search : Use FTS tables along with normal SQLite DB Tables

android sqlite full-text-search

This is more of a design question - not just a coding question.

Perl query and get column name

mysql perl

I need to make a query where I will be looking for a specific string through several columns and I need to know which column (name) contains the value that I need.