How to tell if the GC is running?

Rainer Schuetze r.sagitario at gmx.de
Tue Apr 8 23:16:07 PDT 2014



On 06.04.2014 23:20, Tomer Filiba wrote:
> On Sunday, 6 April 2014 at 16:34:02 UTC, safety0ff wrote:
>> Please post more of the stack trace, it looks like you're allocating
>> while it is running the destructors / finalization (#11408.)
>>
>> https://d.puremagic.com/issues/show_bug.cgi?id=11408
>
> Yes, I know I'm allocating while the GC is collecting. I'm asking how to
> avoid this situation -- is there some way to tell that the GC is running?

If you don't use explicite or scoped destruction, all class object 
destructors are called from the GC finalization, so you might just call 
a different function from class destructors. For structs, they are 
(currently) not finalized if heap allocated, but their destructor is 
called for struct fields of a class.

To implement a check: this is very implementation specific, but the GC 
has an internal variable "running" that is set during collection.

The problem is how to read this variable. This involves accessing the 
private global _gc in gc.proxy. If you are ok with modifying the 
runtime, add a method to gc.proxy like this:

bool gc_iscollecting() { return _gc.gcx.running; }

(you can make this a template function to avoid having to rebuild the 
library).

The even hackier solution is to use the mangled name of the private 
variable somewhere in your code:

import gc.gc;
extern(C) extern __gshared gc.gc.GC _D2gc5proxy3_gcC2gc2gc2GC;

bool gc_iscollecting() { return _D2gc5proxy3_gcC2gc2gc2GC.gcx.running; }

(Depending on the architecture/platform, you might have to remove the 
leading underscore from that identifier).

For both approaches you will have to add druntime/src to your import 
paths, as the gc modules are not part of the modules in the 
druntime/import folder.


More information about the Digitalmars-d mailing list