Greedy memory handling

Dmitry Olshansky dmitry.olsh at gmail.com
Wed Sep 11 04:38:46 PDT 2013


11-Sep-2013 14:34, monarch_dodra пишет:
> On Wednesday, 11 September 2013 at 10:28:37 UTC, Gary Willoughby wrote:
>> You can then let the GC handle it or free it yourself with
>> GC.free(*buffer).
>
> But if the buffer is stored in a static variable, the GC will never
> collect it. I *could* also free it myself, but why/when would I do that?
>
> Did you just just let your buffer grow, and never let it get collected?
>
> Is there a way to do something like "I'm using this buffer, but if you
> want to collect it, then go ahead. I'll reallocate a new one *if/when* I
> need it again"

You need weak references. With manually registered finalize for your 
buffer + flag you might pull it off (but be extremely careful).
There is something like this in an upcoming std.signals2 IIRC.

Basically the sequence should be - pin the pointer with strong ref if 
it's valid, use it, unpin. If it wasn't valid - it got collected, 
allocate new buffer and repeat. The "was valid" is the ugly part, and 
prone to race condition (GC works in its own thread, got to 
disable/enable etc.).

All in all this is the kind of stuff that:
a) Druntime/Phobos should provided
b) Is actually needed for other things as well

I'd file an enhancement if there isn't one already.
-- 
Dmitry Olshansky


More information about the Digitalmars-d-learn mailing list