[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: to-be-closed variables as resources from a library.
- From: Francisco Olarte <folarte@...>
- Date: Thu, 29 Sep 2022 18:14:12 +0200
On Wed, 28 Sept 2022 at 16:24, Jorge Visca <xxopxe@gmail.com> wrote:
> On 28/9/22 04:25, Francisco Olarte wrote:
> > They are just a variation of try/finally, similar to
> > try-with-resources, not that difficult to understand.
> My problem was that in my mind "going out of scope" was "going out of
> scope everywhere in the program". Yes I see that that's not how Lua's gc
> works.
Well GC works with unreachable VALUES. Local work with variables,
which reference obejcts. Remember global in lua are syntactic sugar
for table accesses, you have a hidden local table which is where
"globals" go.
> So, my takeaways (basically derived from what you describe):
> * i'll not use <close> variables anywhere i do not have full control of
> them or they can leak, nor depend on __close for the system to be correct.
> * Conceptually, the main place to release stuff is __gc. Define __close
> to call __gc to speed up memory release when the user mind it enough.
> * All releasing should be idempotent, always.
> * Treat <close> as a memory use optimization, to be used when matters
> where it matters.
I am used to think as all objects must be closed(), <close> is a
helper for code clarity when I need speedy release, __gc is a safety
net.
The problem is garbage collected languages need some kind of
try-finally for timely release. Ref counted do not, but need a way to
avoid loops and are slower. On some language you can have different
kinds of resource management, but mixing them is hard ( i.e. in C++
you can use immediate objects, GC for some things, memory arenas ( the
kind which are freed as a single unit, great for some memory uses )
for others, ref counted for others, but mixing them is difficult.
Immediate objects / ref counted play more or less well with one
another, but gc and arenas do not mix well amongst them and with the
others.
For heavy objects, like files, db connections, locks, ref counted is
normally very good if you can avoid the loops. You can simulate them
with <close> more or less ( I tested it, do a ref-counted base which
closes() on refs and have the library return a refptr class which only
is stored in <close>, or inside a manager. It works, but needs
discipline.
At the end, there is no silver bullet. When I need complex timely
closing of resources I just use another language to manage them (
sometimes it is the C++ host of the lua code ) .
Francisco Olarte.