GC-proof resource classes

ponce via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 30 13:44:15 PDT 2015


On Sunday, 30 August 2015 at 17:00:23 UTC, ZombineDev wrote:
> On Saturday, 29 August 2015 at 13:14:26 UTC, ponce wrote:
>>
>> ----------------
>>
>> ensureNotInGC() is implemented like this:
>>
>> ----------------
>>
>> void ensureNotInGC(string resourceName) nothrow
>> {
>>     debug
>>     {
>>         import core.exception;
>>         try
>>         {
>>             import core.memory;
>>             void* p = GC.malloc(1); // not ideal since it 
>> allocates
>>             return;
>>         }
>>         catch(InvalidMemoryOperationError e)
>>         {
>>             import core.stdc.stdio;
>>             fprintf(stderr, "Error: clean-up of %s incorrectly 
>> depends on destructors called by the GC.\n", resourceName.ptr);
>>             assert(false); // crash
>>         }
>>     }
>> }
>>
>> --------------
>>
>>...
>
> BTW, you can use GC.free, instead of GC.malloc, with any 
> non-zero invalid memory address, for example: 
> http://dpaste.dzfl.pl/af0dc9aaa29d
>

In the case the destructor isn't called by the GC, the call must 
succeed.
GC.malloc(1) fits the bill but it's a waste of time and memory 
indeed. GC.free(<invalid-adress>) would fail in both cases if I 
understand correctly.

> A more robust solution would be to check if the gcx.running 
> flag is raised, or if the GC lock is taken, like this: 
> https://gist.github.com/ZombineDev/14076777dff7d879d659, 
> however this is not currently possible, because the _gc 
> variable in gc.proxy is private and by default gc.proxy is not 
> part of the include files.

Those two would work better than GC.malloc indeed. A nice thing 
is that it seems we don't need synchronization so _gc.gcx.running 
would be ideal.

> Since it's really straightforward to expose the information to 
> the user, I think this would an easy enhancement.

Perhaps as a getter like GC.isRunning()?



More information about the Digitalmars-d mailing list