RC and GC coexistence

Oren Tirosh via Digitalmars-d digitalmars-d at puremagic.com
Sat Sep 20 12:48:07 PDT 2014


Hi everyone. Unlurking to make my first comment here.

Here is an idea for making RC and GC coexist peacefully. I think 
this technique may be used to make the Throwable transition to RC 
while keeping full backward compatibility.

A Throwable object would have a reference counter to track the 
number of RC references to it. It would also have a flag 
indicating whether there are any outstanding GC references to the 
object as well. This flag may be implemented by setting the MSB 
of the reference counter.

RC references would be a different type from GC references. An RC 
reference may be converted to a GC reference by setting the MSB, 
indicating that there may be one or more uncounted references to 
the object and that it should not be destroyed until successfully 
reclaimed by the GC. This RC to GC conversion may happen when a 
reference to a Throwable leaves @nogc code and enters GC land. 
When a GC operation can find no more references to the Throwable 
it would clear the counter MSB. If the number of RC references is 
zero at this point the object would be immediately destroyed.

A crucial part of making this work is to ensure that RC 
references are *not* seen by GC scanning. This may be done by 
mangling the pointer value in some way. Alternatively, if 
mark-and-sweep is replaced with count-and-sweep the number of 
counted RC references may be deducted.

One way to mangle the pointer is to decrement the value to a 
lower memory address. Incrementing the pointer won't work because 
the D garbage collector must handle inner references for slices 
etc.  Any dereferencing of the RC reference would compensate for 
this offset by incrementing the field offset. An obvious piece of 
information to put in the location reserved by decrementing the 
pointer would the the reference counter itself. Conversion of RC 
reference to GC would require incrementing the pointer and 
setting the counter MSB. Converting GC reference to RC is done by 
just decrementing the pointer.

I'm sure there are many things I'm missing here, but could 
something along these line be made to work?


More information about the Digitalmars-d mailing list