Re: Weak references for GObject



Dan Bornstein <danfuzz milk com> writes:

> I wrote:
> >You can think of it as if [the soft ref/unref] functions manipulate the
> >refcount just like normal ref/unref, except there's a side table mapping
> >softly-referenced objects to their soft refcount. When memory gets tight
> >(however you want to define that), you look at that side table and find
> >objects whose only refcounts are due to soft references, and those are the
> >ones that are subject to immediate destruction. When that happens, the
> >notify functions are called, just as with weak references.
> 
> Owen Taylor writes:
> >I thought about this, but decided:
> >
> > - To make this work, it would involve calling finalizers out of
> >   g_malloc(), which could result in all sorts of reentrancy problems,
> >   locking problems, etc.
> 
> If the semantics requires prompt finalization, then I can't argue with
> that. However, if you can defer finalization until the next time that it
> "normally" happens (at unref/destroy time only? apologies for my continued
> lack of depth of knowledge of the gtk internals), then it's no longer an
> issue.
> 
> Or when you say "finalization" do you mean pre-mortem finalization, where
> the contents of the object are still available to the finalization code? If
> so, then, yeah, you're SOL. But (bait bait) everyone knows that pre-mortem
> finalization is frought with problems, which is why everyone should be
> using weak references to do finalization in the first place.

The difference here is that in Java, weak references look like:

 A => weak_reference  => B

An when A dereferences the weak reference, the weak reference temporarily 
becomes a strong reference. So you can do "post-mortem" finalization
by clearing the weak reference and then notifiying later; A can't
accidentally access B after it is gone since the reference has
been cleared when B actually goes away.

However, in GTK+ / C terms, a weak reference looks like:
  
 A ===========> B
 <- notifier -

So, if you do post-morten notification of weak references, you have a
time period when A has a invalid pointer but hasn't been notified of
it.

We don't want to use the Java style for GTK+, because it would be
quite painful with explicit reference counting (and a bit inefficient)

 object = g_weak_ref_deref (blah->weak);
 [ do something with object ]
 g_object_unref (object);

That's one half of the problem - the other half of the problem
is that without garbage collection, the finalization method
on objects needs to typically be quite heavyweight and do
stuff that you simply don't want to do in g_malloc().

Regards,
                                        Owen




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]