GC-proof resource classes

ponce via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 30 14:59:58 PDT 2015


On Sunday, 30 August 2015 at 21:52:37 UTC, ZombineDev wrote:
> On Sunday, 30 August 2015 at 20:44:17 UTC, ponce wrote:
>> 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.
>
> As you can see from the output 
> (http://dpaste.dzfl.pl/aa004554034a), when 
> GC.free(cast(void*)1) is called in main() it doesn't throw. It 
> only throws in the destructor of A, because a GC collection is 
> taking place.
>
> If you look at the implementation, it is more or less 
> guaranteed that:
> a) GC.free() during collection -> InvalidMemoryOperationError 
> [1]
> b) GC.free() with invalid pointer -> no-op [2]
>

Cool thing.

>> Perhaps as a getter like GC.isRunning()?
>
> Yeah, that's what I had in mind. But maybe it also makes sense 
> to provide a way to take the GC lock? Of course, such method 
> should definitely be marked as @system.
>
> [1]: 
> https://github.com/D-Programming-Language/druntime/blob/master/src/gc/gc.d#L879
> [2]: 
> https://github.com/D-Programming-Language/druntime/blob/master/src/gc/gc.d#L888

I'm not sure there is even a need for synchronization since other 
threads that wan't to allocate try to take the GC lock while the 
GC-hijacked thread calls destructors.

And if the destructor isn't called by the GC, I don't see a 
problem either.tre


More information about the Digitalmars-d mailing list