Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Memory Ordering Consistency

Let's say I have the following code:

void* p0 = nullptr;
void* p1 = alloc_some_data();
void f1() {
    p0 = p1;
    p1 = nullptr;
}

Suppose f1 is run on thread 1. Is it possible that (leaving the code as it is) another thread may at some point see p0 and p1 as nullptr (if compiler or hardware reorders instructions such as the second assignment happens before the first)?

The reason I'm asking this is because I want to implement a garbage collector and I want to know if I need to access pointers from the GC thread using atomic instructions (std::atomic). There's no problem if the GC thread sees p0 == p1 == alloc_some_data() but there will be problems if the GC thread sees p0 == p1 == nullptr because then it will report the data previously in p1 as unreachable when it's clearly is reachable.

like image 324
Danilo Carvalho Avatar asked Dec 28 '25 16:12

Danilo Carvalho


1 Answers

If you read an object in one thread which is written by another thread without synchronization you have a data race. This clearly implies that your garbage collector will need to read the values using some sort of synchronization. With respect to your original question: there is nothing in your code indicating that the write to p0 becomes visible prior to the write of p1, i.e., another thread can, indeed, see both to be null. This is independent of the synchronization primitives used to communicate with another thread: there is no ordering between these two writes.

like image 197
Dietmar Kühl Avatar answered Dec 30 '25 06:12

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!