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.
Yes. While not necessarily likely, it is entirely possible because those operations are not atomic.
One (of a few possible scenarios) is this:
You need to use some form of access control (ie a mutex).