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

后端 未结 3 1168
时光说笑
时光说笑 2021-01-04 00:59

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         


        
3条回答
  •  醉梦人生
    2021-01-04 01:29

    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.

提交回复
热议问题