[Gc] Re: Add a new GC pointer tracing mode
zach.saw at gmail.com
Thu Nov 8 14:54:07 PST 2012
> I now almost see how this can work for a single thread. But I’m still not
> sure how to make it reliable with multiple threads and a conventional
> compiler. It seems to me that you would have to make both the pointer and
> the magic number in a gc_ptr atomic, or possibly volatile, to prevent the
> compiler from e.g. delaying the assignment to the magic number, or
> optimizing it out completely as dead code.
> The magic number is assigned when the gc_ptr is created (i.e. c'tor) while
the pointer itself is assigned to the gc_ptr via a copy c'tor or a =
operator. To prevent the compiler from optimizing out the magic number, we
will indeed need to declare it volatile. The gc_ptr class should be along
the following lines:
template <typename T>
// c'tors -- (volatile)m_Ptr=null and assign m_MagicNumber
volatile size_t m_MagicNumber;
I believe assignments to member vars can't be optimized out as the compiler
cannot know if pointer manipulation could effectively end up addressing
m_MagicNumber during runtime. However, we do need to cast m_Ptr to volatile
when we are assigning it NULL prior to assigning m_MagicNumber in gc_ptr's
c'tors. Again, this does not need to be atomic -- if m_MagicNumber is yet
to be assigned, the GC marker simply skips this particular gc_ptr since it
is not fully constructed. Note that the order of assigning the ptr and
magic number is important. For example, in a copy c'tor, we will need to
first assign ptr to NULL, then magic number followed by the actual ptr.
> I also don’t think there is anything preventing a compiler from register
> allocating the two halves of a gc_ptr whose address is never taken. It
> sounds to me like that would still break even single-threaded code.
So far with my limited experience on portability, I have yet to encounter
one that does that for an object. My thinking is that a pointer could be
referring to this particular object at some point during runtime and the
compiler would not have any prior knowledge to be able to optimize it out.
If it does optimize out, it must be 100% sure that the gc_ptr is an unused
variable. In this case, it is fully acceptable.
I’m much less concerned about handling code that has data races on a
> gc_ptr. It seems to me the trick is to prevent the compiler from breaking
> data-race-free code.
> As I said above, the magic number and pointer are rather orthogonal to
each other. The only thing we need to make sure is the sequence they are
assigned so at any point in time if GC kicks in, we will never have a
partially valid gc_ptr (i.e. magic number is valid but ptr is random).
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Gc