[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:31:07 +0200
On Wed, 28 Sept 2022 at 19:10, Jorge Visca <xxopxe@gmail.com> wrote:
> Thinking a bit more, in some cases I still can use <close> to obtain
> something like this, as long as the library's API keeps de <close>
> variables inside the library.
Remember <close> is a modifier to local. It is a helper for the
library user to notify your library he is done with your resource.
You can have your objects keep a ref_count method, put a method ref()
which increments it and returns self, put a unref() method which
decrements ref and destroys the object ( let's say by calling
close(in_gc=false) ), make __close() call unref(), make your normal
constructor return with ref_count=1, lests call this new() do another
one, or an overload, returning with ref_count=other value, specially
zero, lets call this create(), make __gc call close(in_gc=true)). Then
make close warn if in_gc is false and free the resources or, if you
prefer to, refuse to work in this case.
In your documentation you can advise your user to use new and put the
result in <close> variables, and pass obj.ref() to functions which
want to take ownership or just obj to the ones which are simpler
users. When receiving the object the ownership taking function should
put it immediately in a local<close>. To store inside other objects
you use obj.ref() too and make sure to call unref() in the other
object "destructor" or before zapping the stored reference ( if the
ownership taking function puts it in an object, it can shortcircuit
the local+extra ref ). Then instruct your users to either new() into a
local<close> or use create() if they want to explicitly call close()
( and this is a pattern they are going to need some times ).
All of this introduces ref-loop possibilities, but they can "easily"
be dealt with by weak tables.
More or less, this takes a minimum discipline on your users, but
dealing with finite resources is not for the faint of heart.
Francisco Olarte.