[pm-h] When to use "weaken"?

G. Wade Johnson gwadej at anomaly.org
Thu Jan 23 17:30:47 PST 2014


On Thu, 23 Jan 2014 14:07:23 -0800 (PST)
"Michael R. Davis" <mrdvt92 at yahoo.com> wrote:

> Perl Folks,
> I've never really used Perl for processes that run for a very long
> time.  But, I'm moving around and processing data on the scale of
> millions and millions. My issue is that I have a memory leak
> somewhere. 
> I think it's in a statement like this.
>  
> my $profile=XXX::Profiles::Profile->new(name=>$name, parent=>$self);
> 
> where it is important for the child object to know who's it's parent
> is.  But, I guess the garbage collector is not cleaning this up when
> both the parent and child go out of scope. I don't think this is a
> "circular" reference (I called it a tree; like family tree) but it's

If I'm understanding you, that's the definition of a circular reference.

     parent -> child -> parent

In this case, the parent owns the child and the child owns the parent.
You should weaken the child's reference to the parent (because the
child doesn't own the parent.)

> all I've got as to an inkling of an idea of where my memory leak
> might be. Is this the use case for weaken?  If so, where would you
> put the weaken statement, in the parent or the child. for example in
> parent 
> weaken $profile->{"parent"}; #but now the parent has to know about
> the internals of the child 
> in the child

I would do the weaken in the the child. You are passing the parent
reference to the child. The child knows that it doesn't need to own the
parent reference, so the child should weaken the reference.

> sub new {
> ...
>  weaken $self->{"parent"} if (exists($self->{"parent"})
> and ref($self->{"parent"})); #don't want to auto vivify. }
>  
> Am I correct in thinking this is a use case of weaken at all?
>  
> It also bothers me that Fedora appears to not get all of the memory
> back after the Perl process terminates.  Is that common? 

How are you determining whether Fedora "gets all of the memory back"?

G. Wade
-- 
When they first built the University of California at Irvine they just
put the buildings in. They did not put any sidewalks, they just planted
grass. The next year, they came back and put the sidewalks where the
trails were in the grass. Perl is just that kind of language. It is not
designed from first principles. Perl is those sidewalks in the grass.
                                                       -- Larry Wall


More information about the Houston mailing list